diff --git a/packages/web-ui/src/components/ui/DataGrid.tsx b/packages/web-ui/src/components/ui/DataGrid.tsx
index 1b4c07925..f62b5da7f 100644
--- a/packages/web-ui/src/components/ui/DataGrid.tsx
+++ b/packages/web-ui/src/components/ui/DataGrid.tsx
@@ -76,7 +76,7 @@ import {
DATA_GRID_MIN_COLUMN_WIDTH,
DATA_GRID_MAX_COLUMN_WIDTH,
formatCellValue,
- getColumnSortState,
+ getColumnSortInfo,
calculateSelectionRange,
toggleSetValue,
getResultValueType,
@@ -293,7 +293,7 @@ interface DataGridProps {
csvDelimiter?: string;
csvIncludeHeaders?: boolean;
sortClause?: string;
- onSort?: (colName: string) => void;
+ onSort?: (colName: string, options: {additive: boolean}) => void;
readonly?: boolean;
/**
* Total rows in the full result set when known (server-side pagination).
@@ -1868,6 +1868,11 @@ export const DataGrid = React.memo(function DataGrid({
const coreRowModel = useMemo(() => getCoreRowModel(), []);
+ const sortClauseInfo = useMemo(
+ () => getColumnSortInfo(columns, sortClause),
+ [columns, sortClause],
+ );
+
const tableColumns = React.useMemo(
() =>
columns.map((colName, index) =>
@@ -1877,7 +1882,8 @@ export const DataGrid = React.memo(function DataGrid({
// return columns with an empty name, which would otherwise crash the grid.
id: colName !== '' ? colName : `__unnamed_${index}__`,
header: () => {
- const sortState = getColumnSortState(colName, sortClause);
+ const columnSortInfo = sortClauseInfo.byColumn.get(colName);
+ const sortState = columnSortInfo?.direction ?? null;
const displaySortState: 'none' | 'asc' | 'desc' = sortState ?? 'none';
const sortAction = getSortButtonAction(
displaySortState,
@@ -1889,6 +1895,14 @@ export const DataGrid = React.memo(function DataGrid({
: sortAction === 'desc'
? t('dataGrid.sortByDesc', {col: colName})
: t('dataGrid.clearSort');
+ const sortPriority = columnSortInfo?.priority ?? null;
+ const priorityLabel =
+ sortPriority !== null && sortClauseInfo.termCount >= 2
+ ? t('dataGrid.sortPriority', {priority: sortPriority})
+ : null;
+ const accessibleSortButtonLabel = priorityLabel
+ ? `${sortButtonLabel}, ${priorityLabel}`
+ : sortButtonLabel;
// Column data type for the DataGrip-style header hover tooltip.
// Only populated when column metadata is present (i.e. table
// browse), not for arbitrary query results.
@@ -1929,16 +1943,18 @@ export const DataGrid = React.memo(function DataGrid({
)}
{hasMetadataTooltip && (
@@ -1982,7 +2006,7 @@ export const DataGrid = React.memo(function DataGrid({
columns,
columnHelper,
t,
- sortClause,
+ sortClauseInfo,
defaultSortDirection,
onSort,
columnTypeMap,
diff --git a/packages/web-ui/src/i18n/locales/de.json b/packages/web-ui/src/i18n/locales/de.json
index 9d5a6307c..f96808119 100644
--- a/packages/web-ui/src/i18n/locales/de.json
+++ b/packages/web-ui/src/i18n/locales/de.json
@@ -1779,6 +1779,7 @@
"sortByAsc": "Nach {{col}} ASC sortieren",
"sortByDesc": "Nach {{col}} DESC sortieren",
"clearSort": "Sortierung löschen",
+ "sortPriority": "Sortierpriorität {{priority}}",
"copyCell": "Zelle kopieren",
"copyRow": "Zeile kopieren",
"selectAll": "Alle auswählen",
diff --git a/packages/web-ui/src/i18n/locales/en.json b/packages/web-ui/src/i18n/locales/en.json
index 20cf95385..ea969fcb9 100644
--- a/packages/web-ui/src/i18n/locales/en.json
+++ b/packages/web-ui/src/i18n/locales/en.json
@@ -1852,6 +1852,7 @@
"sortByAsc": "Sort by {{col}} ASC",
"sortByDesc": "Sort by {{col}} DESC",
"clearSort": "Clear sort",
+ "sortPriority": "Sort priority {{priority}}",
"copyCell": "Copy Cell",
"copyRow": "Copy Row",
"selectAll": "Select All",
diff --git a/packages/web-ui/src/i18n/locales/es.json b/packages/web-ui/src/i18n/locales/es.json
index ac4249fe1..e24057908 100644
--- a/packages/web-ui/src/i18n/locales/es.json
+++ b/packages/web-ui/src/i18n/locales/es.json
@@ -1810,6 +1810,7 @@
"sortByAsc": "Ordenar por {{col}} ASC",
"sortByDesc": "Ordenar por {{col}} DESC",
"clearSort": "Quitar ordenamiento",
+ "sortPriority": "Prioridad de orden {{priority}}",
"copyCell": "Copiar Celda",
"copyRow": "Copiar Fila",
"selectAll": "Seleccionar Todo",
diff --git a/packages/web-ui/src/i18n/locales/fr.json b/packages/web-ui/src/i18n/locales/fr.json
index 8793fee37..cb366bda0 100644
--- a/packages/web-ui/src/i18n/locales/fr.json
+++ b/packages/web-ui/src/i18n/locales/fr.json
@@ -1819,6 +1819,7 @@
"sortByAsc": "Trier par {{col}} ASC",
"sortByDesc": "Trier par {{col}} DESC",
"clearSort": "Effacer le tri",
+ "sortPriority": "Priorité de tri {{priority}}",
"copyCell": "Copier la cellule",
"copyRow": "Copier la ligne",
"selectAll": "Tout sélectionner",
diff --git a/packages/web-ui/src/i18n/locales/it.json b/packages/web-ui/src/i18n/locales/it.json
index 82b414733..75388e2f6 100644
--- a/packages/web-ui/src/i18n/locales/it.json
+++ b/packages/web-ui/src/i18n/locales/it.json
@@ -1846,6 +1846,7 @@
"sortByAsc": "Ordina per {{col}} ASC",
"sortByDesc": "Ordina per {{col}} DESC",
"clearSort": "Rimuovi ordinamento",
+ "sortPriority": "Priorità di ordinamento {{priority}}",
"copyCell": "Copia cella",
"copyRow": "Copia riga",
"selectAll": "Seleziona Tutti",
diff --git a/packages/web-ui/src/i18n/locales/ja.json b/packages/web-ui/src/i18n/locales/ja.json
index 89656036a..eeda6a3a3 100644
--- a/packages/web-ui/src/i18n/locales/ja.json
+++ b/packages/web-ui/src/i18n/locales/ja.json
@@ -1792,6 +1792,7 @@
"sortByAsc": "{{col}} を昇順で並べ替え",
"sortByDesc": "{{col}} を降順で並べ替え",
"clearSort": "並べ替えを解除",
+ "sortPriority": "並べ替え優先順位 {{priority}}",
"copyCell": "セルをコピー",
"copyRow": "行をコピー",
"selectAll": "すべて選択",
diff --git a/packages/web-ui/src/i18n/locales/ko.json b/packages/web-ui/src/i18n/locales/ko.json
index 2f5397da2..6004b7729 100644
--- a/packages/web-ui/src/i18n/locales/ko.json
+++ b/packages/web-ui/src/i18n/locales/ko.json
@@ -1744,6 +1744,7 @@
"sortByAsc": "{{col}} 오름차순 정렬",
"sortByDesc": "{{col}} 내림차순 정렬",
"clearSort": "정렬 해제",
+ "sortPriority": "정렬 우선순위 {{priority}}",
"copyCell": "셀 복사",
"copyRow": "행 복사",
"selectAll": "전체 선택",
diff --git a/packages/web-ui/src/i18n/locales/pt-BR.json b/packages/web-ui/src/i18n/locales/pt-BR.json
index 06574ff3e..75e2cdda0 100644
--- a/packages/web-ui/src/i18n/locales/pt-BR.json
+++ b/packages/web-ui/src/i18n/locales/pt-BR.json
@@ -1848,6 +1848,7 @@
"sortByAsc": "Ordenar por {{col}} ASC",
"sortByDesc": "Ordenar por {{col}} DESC",
"clearSort": "Limpar ordenação",
+ "sortPriority": "Prioridade de ordenação {{priority}}",
"copyCell": "Copiar Célula",
"copyRow": "Copiar Linha",
"selectAll": "Selecionar Tudo",
diff --git a/packages/web-ui/src/i18n/locales/ru.json b/packages/web-ui/src/i18n/locales/ru.json
index f2729abd3..378aedf6d 100644
--- a/packages/web-ui/src/i18n/locales/ru.json
+++ b/packages/web-ui/src/i18n/locales/ru.json
@@ -1783,6 +1783,7 @@
"sortByAsc": "Сортировать по {{col}} ASC",
"sortByDesc": "Сортировать по {{col}} DESC",
"clearSort": "Сбросить сортировку",
+ "sortPriority": "Приоритет сортировки {{priority}}",
"copyCell": "Копировать ячейку",
"copyRow": "Копировать строку",
"selectAll": "Выбрать все",
diff --git a/packages/web-ui/src/i18n/locales/tl.json b/packages/web-ui/src/i18n/locales/tl.json
index e55233a05..b27622a99 100644
--- a/packages/web-ui/src/i18n/locales/tl.json
+++ b/packages/web-ui/src/i18n/locales/tl.json
@@ -1811,6 +1811,7 @@
"sortByAsc": "I-sort ang {{col}} ASC",
"sortByDesc": "I-sort ang {{col}} DESC",
"clearSort": "Alisin ang sort",
+ "sortPriority": "Priyoridad ng pag-uuri {{priority}}",
"copyCell": "Kopyahin ang Cell",
"copyRow": "Kopyahin ang Row",
"selectAll": "Piliin Lahat",
diff --git a/packages/web-ui/src/i18n/locales/vi.json b/packages/web-ui/src/i18n/locales/vi.json
index aa45bf1ed..83763ad19 100644
--- a/packages/web-ui/src/i18n/locales/vi.json
+++ b/packages/web-ui/src/i18n/locales/vi.json
@@ -1835,6 +1835,7 @@
"sortByAsc": "Sắp xếp theo {{col}} tăng dần",
"sortByDesc": "Sắp xếp theo {{col}} giảm dần",
"clearSort": "Bỏ sắp xếp",
+ "sortPriority": "Ưu tiên sắp xếp {{priority}}",
"copyCell": "Sao chép ô",
"copyRow": "Sao chép dòng",
"selectAll": "Chọn tất cả",
diff --git a/packages/web-ui/src/i18n/locales/zh-TW.json b/packages/web-ui/src/i18n/locales/zh-TW.json
index c9fb51964..af234bc89 100644
--- a/packages/web-ui/src/i18n/locales/zh-TW.json
+++ b/packages/web-ui/src/i18n/locales/zh-TW.json
@@ -1857,6 +1857,7 @@
"sortByAsc": "按 {{col}} 升序排序",
"sortByDesc": "按 {{col}} 降序排序",
"clearSort": "清除排序",
+ "sortPriority": "排序優先級 {{priority}}",
"copyCell": "複製儲存格",
"copyRow": "複製列",
"selectAll": "全選",
diff --git a/packages/web-ui/src/i18n/locales/zh.json b/packages/web-ui/src/i18n/locales/zh.json
index 837f64083..e96324eb4 100644
--- a/packages/web-ui/src/i18n/locales/zh.json
+++ b/packages/web-ui/src/i18n/locales/zh.json
@@ -1750,6 +1750,7 @@
"sortByAsc": "按 {{col}} 升序排序",
"sortByDesc": "按 {{col}} 降序排序",
"clearSort": "清除排序",
+ "sortPriority": "排序优先级 {{priority}}",
"copyCell": "复制单元格",
"copyRow": "复制行",
"selectAll": "全选",
diff --git a/packages/web-ui/src/pages/Editor.tsx b/packages/web-ui/src/pages/Editor.tsx
index a38483284..d7004f40a 100644
--- a/packages/web-ui/src/pages/Editor.tsx
+++ b/packages/web-ui/src/pages/Editor.tsx
@@ -30,7 +30,7 @@ import {
getLoadedRowsExportLimit,
type ResultExportFormat,
} from '@/utils/resultExport';
-import {serializePkKey, buildPkMap} from '@/utils/dataGrid';
+import {serializePkKey, buildPkMap, updateSortClause} from '@/utils/dataGrid';
import {
createGridHistory,
recordGridEdit,
@@ -262,7 +262,6 @@ import {
type ColumnStatsSupport,
type PluginColumnStatsFetcher,
} from '@/utils/columnStats';
-import {getNextSortClause} from '@/utils/tableToolbar';
import {clampTabGap, getAdjacentTabGap} from '@/utils/tabDnd';
import {getBulkClosedTabIds} from '@/utils/tabPins';
import {
@@ -3626,14 +3625,15 @@ export const Editor = ({commandScopeId}: EditorProps) => {
);
const handleSort = useCallback(
- (colName: string) => {
+ (colName: string, {additive}: {additive: boolean}) => {
if (!activeTab) return;
const currentSort = activeTab.sortClause || '';
const defaultDir = settings.defaultSortDirection ?? 'asc';
- const newSort = getNextSortClause(
+ const newSort = updateSortClause(
currentSort,
colName,
+ additive,
defaultDir,
activeCapabilities ?? activeDriver,
);
diff --git a/packages/web-ui/src/utils/dataGrid.ts b/packages/web-ui/src/utils/dataGrid.ts
index e0d5af805..2cc0bff7b 100644
--- a/packages/web-ui/src/utils/dataGrid.ts
+++ b/packages/web-ui/src/utils/dataGrid.ts
@@ -7,11 +7,12 @@ import {formatGeometricValue, isGeometricType} from './geometry';
import {formatBlobValue, isBlobColumn, isBlobWireFormat} from './blob';
import {isJsonColumn} from './json';
import type {ResultCommands} from '@/types/commands';
-import {escapeRegExp} from './escape';
import type {FormatTone} from './conditionalFormatting';
import {DEFAULT_FONT_SIZE} from './settings';
-import type {ResultGridDensity} from '@/contexts/SettingsContext';
+import type {DefaultSortDirection, ResultGridDensity} from '@/contexts/SettingsContext';
import {isTextColumn} from './text';
+import {formatSqlIdentifier} from './identifiers';
+import type {DriverCapabilities, PluginManifest} from '@/types/plugins';
/** Sentinel value indicating that the database DEFAULT value should be used */
export const USE_DEFAULT_SENTINEL = '__USE_DEFAULT__';
@@ -538,6 +539,230 @@ export function getResultValueType(value: unknown, columnType?: string): ResultV
return 'string';
}
+interface ParsedSortTerm {
+ identifierParts: string[];
+ direction: Exclude;
+ directionStart: number | null;
+ directionEnd: number | null;
+ directionInsertionIndex: number;
+}
+
+interface SortClauseTerm {
+ raw: string;
+ parsed: ParsedSortTerm | null;
+}
+
+interface ParsedIdentifierPath {
+ parts: string[];
+ end: number;
+}
+
+function splitSortTerms(sortClause: string): string[] {
+ const terms: string[] = [];
+ let start = 0;
+ let quoteEnd: string | null = null;
+ let parenthesisDepth = 0;
+
+ for (let index = 0; index < sortClause.length; index += 1) {
+ const char = sortClause[index];
+ if (quoteEnd) {
+ if (char === quoteEnd) {
+ if (sortClause[index + 1] === quoteEnd) {
+ index += 1;
+ } else {
+ quoteEnd = null;
+ }
+ }
+ continue;
+ }
+
+ if (char === '"' || char === '`' || char === "'") {
+ quoteEnd = char;
+ } else if (char === '[') {
+ quoteEnd = ']';
+ } else if (char === '(') {
+ parenthesisDepth += 1;
+ } else if (char === ')' && parenthesisDepth > 0) {
+ parenthesisDepth -= 1;
+ } else if (char === ',' && parenthesisDepth === 0) {
+ terms.push(sortClause.slice(start, index));
+ start = index + 1;
+ }
+ }
+
+ terms.push(sortClause.slice(start));
+ return terms;
+}
+
+function parseIdentifierPath(term: string, startIndex: number): ParsedIdentifierPath | null {
+ const parts: string[] = [];
+ let index = startIndex;
+
+ while (index < term.length) {
+ while (/\s/.test(term[index] ?? '')) index += 1;
+ if (index >= term.length) return null;
+
+ const opening = term[index];
+ const closing = opening === '[' ? ']' : opening;
+ let part = '';
+
+ if (opening === '"' || opening === '`' || opening === '[') {
+ index += 1;
+ let closed = false;
+ while (index < term.length) {
+ const char = term[index];
+ if (char === closing) {
+ if (term[index + 1] === closing) {
+ part += closing;
+ index += 2;
+ } else {
+ index += 1;
+ closed = true;
+ break;
+ }
+ } else {
+ part += char;
+ index += 1;
+ }
+ }
+ if (!closed) return null;
+ } else {
+ const start = index;
+ while (index < term.length && !/[\s.]/.test(term[index])) index += 1;
+ if (start === index) return null;
+ part = term.slice(start, index);
+ if (/[(),'"`=<>!+*/%|&:;]/.test(part)) return null;
+ }
+
+ parts.push(part);
+ while (/\s/.test(term[index] ?? '')) index += 1;
+ if (term[index] !== '.') break;
+ index += 1;
+ }
+
+ return parts.length === 0 ? null : {parts, end: index};
+}
+
+function isSortKeywordAt(term: string, index: number, keyword: string): boolean {
+ const end = index + keyword.length;
+ return term.slice(index, end).toLowerCase() === keyword && !/[a-z0-9_$]/i.test(term[end] ?? '');
+}
+
+function skipWhitespace(term: string, index: number): number {
+ while (/\s/.test(term[index] ?? '')) index += 1;
+ return index;
+}
+
+function parseSortTerm(raw: string): ParsedSortTerm | null {
+ const term = raw.trim();
+ const identifier = parseIdentifierPath(term, 0);
+ if (!identifier) return null;
+
+ let cursor = identifier.end;
+ let direction: Exclude = 'asc';
+ let directionStart: number | null = null;
+ let directionEnd: number | null = null;
+ let directionInsertionIndex = term.length;
+ let hasCollation = false;
+ let hasNullOrdering = false;
+
+ while ((cursor = skipWhitespace(term, cursor)) < term.length) {
+ const tokenStart = cursor;
+
+ if (isSortKeywordAt(term, tokenStart, 'collate')) {
+ if (hasCollation || directionStart !== null || hasNullOrdering) return null;
+ const collationStart = skipWhitespace(term, tokenStart + 'collate'.length);
+ if (collationStart === tokenStart + 'collate'.length) return null;
+ const collation = parseIdentifierPath(term, collationStart);
+ if (!collation) return null;
+ cursor = collation.end;
+ hasCollation = true;
+ continue;
+ }
+
+ const directionToken = (['asc', 'desc'] as const).find((keyword) =>
+ isSortKeywordAt(term, tokenStart, keyword),
+ );
+ if (directionToken) {
+ if (directionStart !== null || hasNullOrdering) return null;
+ direction = directionToken;
+ directionStart = tokenStart;
+ directionEnd = tokenStart + directionToken.length;
+ cursor = directionEnd;
+ continue;
+ }
+
+ if (isSortKeywordAt(term, tokenStart, 'nulls')) {
+ if (hasNullOrdering) return null;
+ const orderingStart = skipWhitespace(term, tokenStart + 'nulls'.length);
+ if (orderingStart === tokenStart + 'nulls'.length) return null;
+ const ordering = ['first', 'last'].find((keyword) =>
+ isSortKeywordAt(term, orderingStart, keyword),
+ );
+ if (!ordering) return null;
+ if (directionStart === null) directionInsertionIndex = tokenStart;
+ cursor = orderingStart + ordering.length;
+ hasNullOrdering = true;
+ continue;
+ }
+
+ return null;
+ }
+
+ return {
+ identifierParts: identifier.parts,
+ direction,
+ directionStart,
+ directionEnd,
+ directionInsertionIndex,
+ };
+}
+
+function parseSortClause(sortClause: string | undefined): SortClauseTerm[] {
+ if (!sortClause) return [];
+ return splitSortTerms(sortClause)
+ .map((raw) => ({raw, parsed: parseSortTerm(raw)}))
+ .filter((term) => term.raw.trim().length > 0);
+}
+
+function sortTermMatchesColumn(term: ParsedSortTerm, columnName: string): boolean {
+ const normalizedColumn = columnName.toLowerCase();
+ return (
+ term.identifierParts.join('.').toLowerCase() === normalizedColumn ||
+ term.identifierParts.some((part) => part.toLowerCase() === normalizedColumn)
+ );
+}
+
+function findSortTermIndex(terms: SortClauseTerm[], columnName: string): number {
+ return terms.findIndex(
+ (term) => term.parsed !== null && sortTermMatchesColumn(term.parsed, columnName),
+ );
+}
+
+function updateSortTermDirection(
+ term: SortClauseTerm,
+ direction: Exclude,
+): string {
+ const parsed = term.parsed;
+ if (!parsed) return term.raw.trim();
+
+ const raw = term.raw.trim();
+ const formattedDirection = direction.toUpperCase();
+ if (parsed.directionStart !== null && parsed.directionEnd !== null) {
+ return (
+ raw.slice(0, parsed.directionStart) +
+ formattedDirection +
+ raw.slice(parsed.directionEnd)
+ );
+ }
+
+ const before = raw.slice(0, parsed.directionInsertionIndex);
+ const after = raw.slice(parsed.directionInsertionIndex);
+ const spaceBefore = before && !/\s$/.test(before) ? ' ' : '';
+ const spaceAfter = after && !/^\s/.test(after) ? ' ' : '';
+ return `${before}${spaceBefore}${formattedDirection}${spaceAfter}${after}`;
+}
+
/**
* Determines the sort state for a column based on the current sort clause
* @param columnName - The column to check
@@ -548,29 +773,96 @@ export function getColumnSortState(
columnName: string,
sortClause: string | undefined,
): SortDirection {
- if (!sortClause) return null;
-
- // Strip identifier quotes so postgres clauses like "Status" DESC match column names
- const clauseForMatch = sortClause.replace(/"([^"]*)"/g, '$1').replace(/`([^`]*)`/g, '$1');
- const normalizedClause = clauseForMatch.toLowerCase();
- const normalizedCol = columnName.toLowerCase();
-
- const patterns = [
- new RegExp(`\\b${escapeRegExp(normalizedCol)}\\s+(asc|desc)\\b`),
- new RegExp(`\\b${escapeRegExp(normalizedCol)}\\b`),
- ];
-
- for (const pattern of patterns) {
- const match = normalizedClause.match(pattern);
- if (match) {
- if (match[1]) {
- return match[1] === 'asc' ? 'asc' : 'desc';
- }
- return 'asc';
+ const terms = parseSortClause(sortClause);
+ const index = findSortTermIndex(terms, columnName);
+ return index === -1 ? null : (terms[index].parsed?.direction ?? null);
+}
+
+/** Returns the 1-based position of a column in the sort clause, or null when absent. */
+export function getColumnSortPriority(
+ columnName: string,
+ sortClause: string | undefined,
+): number | null {
+ const index = findSortTermIndex(parseSortClause(sortClause), columnName);
+ return index === -1 ? null : index + 1;
+}
+
+/** Parses the clause once and returns sort state and priority for the requested columns. */
+export function getColumnSortInfo(
+ columnNames: readonly string[],
+ sortClause: string | undefined,
+): {
+ byColumn: Map;
+ termCount: number;
+} {
+ const terms = parseSortClause(sortClause);
+ const info = new Map();
+
+ for (const columnName of columnNames) {
+ const index = findSortTermIndex(terms, columnName);
+ if (index === -1) continue;
+
+ const parsed = terms[index].parsed;
+ if (parsed) info.set(columnName, {direction: parsed.direction, priority: index + 1});
+ }
+
+ return {byColumn: info, termCount: terms.length};
+}
+
+/**
+ * Updates a grid sort clause for a normal or additive (Shift) column-header click.
+ * A normal click replaces the clause; additive clicks preserve all other terms.
+ */
+export function updateSortClause(
+ currentSortClause: string | undefined,
+ columnName: string,
+ additive: boolean,
+ defaultSortDirection: DefaultSortDirection = 'asc',
+ driver?: string | PluginManifest | DriverCapabilities | null,
+): string {
+ const terms = parseSortClause(currentSortClause);
+ const activeIndex = findSortTermIndex(terms, columnName);
+ const currentDirection =
+ activeIndex === -1 ? null : (terms[activeIndex].parsed?.direction ?? null);
+ const nextDirection =
+ currentDirection === null
+ ? defaultSortDirection
+ : currentDirection === defaultSortDirection
+ ? defaultSortDirection === 'asc'
+ ? 'desc'
+ : 'asc'
+ : null;
+
+ if (!additive) {
+ if (nextDirection === null) return '';
+ if (activeIndex !== -1) {
+ return updateSortTermDirection(terms[activeIndex], nextDirection);
}
+ return `${formatSqlIdentifier(columnName, driver)} ${nextDirection.toUpperCase()}`;
+ }
+
+ if (activeIndex === -1) {
+ const identifierSql = formatSqlIdentifier(columnName, driver);
+ return [
+ ...terms.map((term) => term.raw.trim()),
+ `${identifierSql} ${defaultSortDirection.toUpperCase()}`,
+ ].join(', ');
}
- return null;
+ if (nextDirection === null) {
+ return terms
+ .filter(
+ (term) => term.parsed === null || !sortTermMatchesColumn(term.parsed, columnName),
+ )
+ .map((term) => term.raw.trim())
+ .join(', ');
+ }
+
+ return terms
+ .map((term, index) =>
+ index === activeIndex ? updateSortTermDirection(term, nextDirection) : term.raw.trim(),
+ )
+ .join(', ');
}
/**
diff --git a/packages/web-ui/src/utils/identifiers.ts b/packages/web-ui/src/utils/identifiers.ts
index 69951585b..729eb36c6 100644
--- a/packages/web-ui/src/utils/identifiers.ts
+++ b/packages/web-ui/src/utils/identifiers.ts
@@ -89,44 +89,19 @@ export function isMysqlDialect(
// PostgreSQL folds unquoted identifiers to lowercase and only needs quotes for
// reserved words, mixed case, or special characters — mirroring quote_ident().
const PG_SAFE_IDENTIFIER = /^[a-z_][a-z0-9_$]*$/;
-const PG_RESERVED = new Set([
- 'select',
- 'from',
- 'where',
- 'table',
- 'user',
- 'order',
- 'group',
- 'join',
- 'and',
- 'or',
- 'as',
- 'in',
- 'on',
- 'by',
- 'null',
- 'true',
- 'false',
- 'default',
- 'check',
- 'column',
- 'limit',
- 'offset',
-]);
/**
* Formats a SQL identifier for WHERE / ORDER BY fragments.
- * Quotes only when required (PostgreSQL); otherwise returns the name unchanged.
+ * Leaves safe identifiers unchanged and uses the driver's configured quote
+ * character when the identifier requires quoting.
*/
export function formatSqlIdentifier(
identifier: string,
driver: string | PluginManifest | DriverCapabilities | null | undefined,
): string {
- if (!shouldQuoteIdentifiers(driver)) return identifier;
- if (PG_SAFE_IDENTIFIER.test(identifier) && !PG_RESERVED.has(identifier)) {
- return identifier;
- }
- return quoteIdentifier(identifier, driver);
+ return identifierNeedsQuoting(identifier, driver)
+ ? quoteIdentifier(identifier, driver)
+ : identifier;
}
export function quoteIdentifier(
diff --git a/packages/web-ui/tests/components/ui/DataGrid.test.tsx b/packages/web-ui/tests/components/ui/DataGrid.test.tsx
index dc3b268df..b79bf8341 100644
--- a/packages/web-ui/tests/components/ui/DataGrid.test.tsx
+++ b/packages/web-ui/tests/components/ui/DataGrid.test.tsx
@@ -1776,13 +1776,14 @@ describe('DataGrid column selection', () => {
});
});
- const renderGrid = (onSort = vi.fn()) => {
+ const renderGrid = (onSort = vi.fn(), sortClause?: string) => {
const utils = render(
,
@@ -1815,7 +1816,47 @@ describe('DataGrid column selection', () => {
expect(container.querySelectorAll('th')[2]).toHaveClass('bg-accent-primary/20');
fireEvent.click(screen.getAllByLabelText('dataGrid.sortByAsc')[0]);
- expect(onSort).toHaveBeenCalledWith('id');
+ expect(onSort).toHaveBeenCalledWith('id', {additive: false});
+ });
+
+ it('passes Shift+click as an additive sort action', () => {
+ const {onSort} = renderGrid();
+
+ fireEvent.click(screen.getAllByLabelText('dataGrid.sortByAsc')[0], {shiftKey: true});
+
+ expect(onSort).toHaveBeenCalledWith('id', {additive: true});
+ });
+
+ it('shows accessible numeric priorities when multiple columns are sorted', () => {
+ const {container} = renderGrid(vi.fn(), 'id ASC, name DESC');
+ const priorityButtons = container.querySelectorAll(
+ 'button[aria-label*="dataGrid.sortPriority"]',
+ );
+
+ expect(priorityButtons).toHaveLength(2);
+ expect(priorityButtons[0]).toHaveAttribute(
+ 'aria-label',
+ expect.stringContaining('dataGrid.sortPriority'),
+ );
+ expect(priorityButtons[0].querySelector('span[aria-hidden="true"]')).toHaveTextContent('1');
+ expect(priorityButtons[1].querySelector('span[aria-hidden="true"]')).toHaveTextContent('2');
+ });
+
+ it('uses the ORDER BY position for a column after an opaque expression', () => {
+ const {container} = renderGrid(vi.fn(), "COALESCE(name, '') ASC, id DESC");
+ const priorityButtons = container.querySelectorAll(
+ 'button[aria-label*="dataGrid.sortPriority"]',
+ );
+
+ expect(priorityButtons).toHaveLength(1);
+ expect(priorityButtons[0].querySelector('span[aria-hidden="true"]')).toHaveTextContent('2');
+ });
+
+ it('does not show a priority badge for a single sort key and keeps its action label', () => {
+ const {container} = renderGrid(vi.fn(), 'id ASC');
+
+ expect(container.querySelectorAll('button > span[aria-hidden="true"]')).toHaveLength(0);
+ expect(screen.getByLabelText('dataGrid.sortByDesc')).toBeInTheDocument();
});
it('copies only the selected columns with Cmd/Ctrl+C', async () => {
diff --git a/packages/web-ui/tests/utils/dataGrid.test.ts b/packages/web-ui/tests/utils/dataGrid.test.ts
index 4b6d31b9d..498ad21f9 100644
--- a/packages/web-ui/tests/utils/dataGrid.test.ts
+++ b/packages/web-ui/tests/utils/dataGrid.test.ts
@@ -2,6 +2,9 @@ import {describe, it, expect, vi} from 'vitest';
import {
formatCellValue,
getColumnSortState,
+ getColumnSortPriority,
+ getColumnSortInfo,
+ updateSortClause,
calculateSelectionRange,
toggleSetValue,
isZebraStripedRow,
@@ -357,6 +360,278 @@ describe('dataGrid utils', () => {
expect(getColumnSortState('Status', '"Status" ASC')).toBe('asc');
expect(getColumnSortState('UserName', '"Status" ASC, "UserName" DESC')).toBe('desc');
});
+
+ it('should parse quoted identifiers containing spaces and commas', () => {
+ expect(getColumnSortState('first, last', '"first, last" DESC, id ASC')).toBe('desc');
+ expect(getColumnSortState('Full Name', '`Full Name` ASC')).toBe('asc');
+ });
+
+ it('should parse escaped quote characters in quoted identifiers', () => {
+ expect(getColumnSortState('say "hi"', '"say ""hi""" DESC')).toBe('desc');
+ expect(getColumnSortState('say `hi`', '`say ``hi``` ASC')).toBe('asc');
+ });
+
+ it('should parse SQL Server bracket identifiers with escaped closing brackets', () => {
+ expect(getColumnSortState('col]name', '[col]]name] DESC')).toBe('desc');
+ expect(getColumnSortState('col, name', '[col, name] DESC, id ASC')).toBe('desc');
+ });
+
+ it('should match quoted qualified identifiers and retain suffix matching', () => {
+ expect(getColumnSortState('users.name', '"users"."name" DESC')).toBe('desc');
+ expect(getColumnSortState('name', '"users"."name" DESC')).toBe('desc');
+ });
+
+ it('does not recognize columns inside unsupported SQL expressions', () => {
+ expect(getColumnSortState('name', "COALESCE(name, '') ASC")).toBeNull();
+ expect(getColumnSortState('id', "CASE WHEN status = 'a,b' THEN id END ASC")).toBeNull();
+ });
+
+ it('recognizes simple columns with COLLATE and NULLS ordering modifiers', () => {
+ expect(getColumnSortState('created_at', 'created_at DESC NULLS LAST')).toBe('desc');
+ expect(getColumnSortState('name', 'name COLLATE NOCASE ASC')).toBe('asc');
+ });
+
+ it('recognizes combined modifiers and omitted direction', () => {
+ expect(getColumnSortState('name', 'name COLLATE NOCASE ASC NULLS FIRST')).toBe('asc');
+ expect(getColumnSortState('name', 'name COLLATE NOCASE NULLS LAST')).toBe('asc');
+ });
+ });
+
+ describe('getColumnSortPriority', () => {
+ it('returns a 1-based position or null when the column is not sorted', () => {
+ const clause = 'name ASC, id DESC, "Full Name" ASC';
+
+ expect(getColumnSortPriority('name', clause)).toBe(1);
+ expect(getColumnSortPriority('ID', clause)).toBe(2);
+ expect(getColumnSortPriority('Full Name', clause)).toBe(3);
+ expect(getColumnSortPriority('age', clause)).toBeNull();
+ expect(getColumnSortPriority('name', '')).toBeNull();
+ });
+
+ it('supports qualified columns and quoted commas', () => {
+ expect(getColumnSortPriority('name', 'users.name ASC, "last, first" DESC')).toBe(1);
+ expect(getColumnSortPriority('last, first', 'users.name ASC, "last, first" DESC')).toBe(
+ 2,
+ );
+ });
+
+ it('counts opaque SQL terms in the actual ORDER BY positions', () => {
+ expect(getColumnSortPriority('id', "COALESCE(name, '') ASC, id DESC")).toBe(2);
+ expect(
+ getColumnSortPriority('id', "CASE WHEN status = 'a,b' THEN id END ASC, id DESC"),
+ ).toBe(2);
+ });
+
+ it('uses the first duplicate term deterministically', () => {
+ const clause = 'id DESC, id ASC, name ASC';
+
+ expect(getColumnSortState('id', clause)).toBe('desc');
+ expect(getColumnSortPriority('id', clause)).toBe(1);
+ });
+
+ it('returns actual positions for both COLLATE and NULLS-modified terms', () => {
+ const clause = 'created_at DESC NULLS LAST, name COLLATE NOCASE ASC';
+
+ expect(getColumnSortPriority('created_at', clause)).toBe(1);
+ expect(getColumnSortPriority('name', clause)).toBe(2);
+ });
+ });
+
+ describe('getColumnSortInfo', () => {
+ it('parses once into state and priority for the requested columns', () => {
+ expect(
+ getColumnSortInfo(
+ ['name', 'id', 'missing'],
+ 'COALESCE(first_name, last_name) ASC, id DESC, name ASC',
+ ),
+ ).toEqual({
+ byColumn: new Map([
+ ['name', {direction: 'asc', priority: 3}],
+ ['id', {direction: 'desc', priority: 2}],
+ ]),
+ termCount: 3,
+ });
+ });
+ });
+
+ describe('updateSortClause', () => {
+ it('starts sorting an unsorted column in the configured default direction', () => {
+ expect(updateSortClause('', 'name', false, 'asc')).toBe('name ASC');
+ expect(updateSortClause(undefined, 'name', true, 'desc')).toBe('name DESC');
+ });
+
+ it('appends a Shift-clicked column without changing existing terms', () => {
+ expect(updateSortClause('name ASC', 'id', true, 'asc')).toBe('name ASC, id ASC');
+ expect(updateSortClause('name ASC, id DESC', 'age', true, 'desc')).toBe(
+ 'name ASC, id DESC, age DESC',
+ );
+ });
+
+ it('preserves opaque terms and their order when adding or changing sort keys', () => {
+ const nullsLast = 'created_at DESC NULLS LAST';
+ const nullsFirst = 'created_at ASC NULLS FIRST';
+ const collate = 'name COLLATE NOCASE ASC';
+ const nested = 'COALESCE(first_name, last_name) ASC';
+ const nestedFunctions = "COALESCE(first_name, CONCAT(last_name, ', suffix')) ASC";
+ const caseExpression = "CASE WHEN status = 'a,''b,c' THEN id END ASC";
+
+ expect(updateSortClause(nullsLast, 'id', true, 'asc')).toBe(`${nullsLast}, id ASC`);
+ expect(updateSortClause(nullsFirst, 'id', true, 'asc')).toBe(`${nullsFirst}, id ASC`);
+ expect(updateSortClause(collate, 'id', true, 'asc')).toBe(`${collate}, id ASC`);
+ expect(updateSortClause(`${nested}, id DESC`, 'age', true, 'asc')).toBe(
+ `${nested}, id DESC, age ASC`,
+ );
+ expect(updateSortClause(nestedFunctions, 'id', true, 'asc')).toBe(
+ `${nestedFunctions}, id ASC`,
+ );
+ expect(updateSortClause(`${caseExpression}, id DESC`, 'id', true, 'asc')).toBe(
+ caseExpression,
+ );
+ expect(updateSortClause(`${nested}, id DESC`, 'age', false, 'asc')).toBe('age ASC');
+ });
+
+ it('changes only the direction for NULLS and COLLATE-modified columns', () => {
+ expect(
+ updateSortClause('created_at ASC NULLS LAST, id DESC', 'created_at', true, 'asc'),
+ ).toBe('created_at DESC NULLS LAST, id DESC');
+ expect(updateSortClause('name COLLATE NOCASE DESC, id ASC', 'name', true, 'desc')).toBe(
+ 'name COLLATE NOCASE ASC, id ASC',
+ );
+ });
+
+ it('inserts a missing direction before NULLS ordering and preserves COLLATE', () => {
+ expect(
+ updateSortClause('name COLLATE NOCASE NULLS LAST, id ASC', 'name', true, 'asc'),
+ ).toBe('name COLLATE NOCASE DESC NULLS LAST, id ASC');
+ });
+
+ it('removes the complete modified term after its sort cycle', () => {
+ expect(
+ updateSortClause('created_at DESC NULLS LAST, id ASC', 'created_at', true, 'asc'),
+ ).toBe('id ASC');
+ expect(
+ updateSortClause(
+ 'name COLLATE NOCASE DESC NULLS FIRST, id DESC',
+ 'name',
+ true,
+ 'asc',
+ ),
+ ).toBe('id DESC');
+ });
+
+ it('preserves clicked modifiers on a normal click while replacing other keys', () => {
+ expect(updateSortClause('name COLLATE NOCASE ASC, id DESC', 'name', false, 'asc')).toBe(
+ 'name COLLATE NOCASE DESC',
+ );
+ });
+
+ it('keeps priorities for multiple modified terms', () => {
+ const clause = 'created_at DESC NULLS LAST, name COLLATE NOCASE ASC';
+ const sortInfo = getColumnSortInfo(['name', 'created_at'], clause);
+
+ expect(sortInfo.byColumn.get('created_at')).toEqual({
+ direction: 'desc',
+ priority: 1,
+ });
+ expect(sortInfo.byColumn.get('name')).toEqual({direction: 'asc', priority: 2});
+ expect(sortInfo.termCount).toBe(2);
+ });
+
+ it('replaces all other sort keys on a normal click', () => {
+ expect(updateSortClause('name ASC, id DESC', 'age', false, 'asc')).toBe('age ASC');
+ });
+
+ it('cycles normal clicks and clears all keys after the second direction', () => {
+ expect(updateSortClause('name ASC, id DESC', 'name', false, 'asc')).toBe('name DESC');
+ expect(updateSortClause('name DESC, id DESC', 'name', false, 'asc')).toBe('');
+ expect(updateSortClause('name DESC, id ASC', 'name', false, 'desc')).toBe('name ASC');
+ expect(updateSortClause('name ASC, id DESC', 'name', false, 'desc')).toBe('');
+ });
+
+ it('cycles ASC to DESC and then removes the key', () => {
+ expect(updateSortClause('name ASC, id DESC', 'name', true, 'asc')).toBe(
+ 'name DESC, id DESC',
+ );
+ expect(updateSortClause('name DESC, id DESC', 'name', true, 'asc')).toBe('id DESC');
+ });
+
+ it('cycles DESC to ASC and then removes the key when the default is DESC', () => {
+ expect(updateSortClause('name DESC, id ASC', 'name', true, 'desc')).toBe(
+ 'name ASC, id ASC',
+ );
+ expect(updateSortClause('name ASC, id DESC', 'name', true, 'desc')).toBe('id DESC');
+ });
+
+ it('cycles an active secondary key while preserving the priority of other keys', () => {
+ const updated = updateSortClause('name ASC, id ASC, age DESC', 'id', true, 'asc');
+
+ expect(updated).toBe('name ASC, id DESC, age DESC');
+ expect(getColumnSortPriority('name', updated)).toBe(1);
+ expect(getColumnSortPriority('id', updated)).toBe(2);
+ expect(getColumnSortPriority('age', updated)).toBe(3);
+ });
+
+ it('removes a key without disturbing remaining order or directions', () => {
+ const updated = updateSortClause('name ASC, id DESC, age ASC', 'id', true, 'asc');
+
+ expect(updated).toBe('name ASC, age ASC');
+ expect(getColumnSortPriority('name', updated)).toBe(1);
+ expect(getColumnSortPriority('age', updated)).toBe(2);
+ });
+
+ it('recalculates priority after removing a secondary key following an opaque term', () => {
+ const clause = "COALESCE(name, '') ASC, id ASC, age DESC";
+ const cycled = updateSortClause(clause, 'id', true, 'asc');
+
+ expect(cycled).toBe("COALESCE(name, '') ASC, id DESC, age DESC");
+ expect(getColumnSortPriority('id', cycled)).toBe(2);
+
+ const removed = updateSortClause(cycled, 'id', true, 'asc');
+ expect(removed).toBe("COALESCE(name, '') ASC, age DESC");
+ expect(getColumnSortPriority('age', removed)).toBe(2);
+ });
+
+ it('removes every duplicate occurrence of the clicked key deterministically', () => {
+ expect(updateSortClause('id DESC, id ASC, name ASC', 'id', true, 'asc')).toBe(
+ 'name ASC',
+ );
+ });
+
+ it('preserves PostgreSQL- and backtick-quoted identifiers while updating them', () => {
+ expect(updateSortClause('"First, Last" ASC, id DESC', 'first, last', true, 'asc')).toBe(
+ '"First, Last" DESC, id DESC',
+ );
+ expect(updateSortClause('`say ``hi``` ASC, id DESC', 'say `hi`', true, 'asc')).toBe(
+ '`say ``hi``` DESC, id DESC',
+ );
+ });
+
+ it('matches column names case-insensitively and recognizes qualified identifiers', () => {
+ expect(updateSortClause('users.name ASC, id DESC', 'NAME', true, 'asc')).toBe(
+ 'users.name DESC, id DESC',
+ );
+ expect(updateSortClause('users.name ASC, id DESC', 'users.name', true, 'asc')).toBe(
+ 'users.name DESC, id DESC',
+ );
+ });
+
+ it('formats newly added identifiers with the active driver', () => {
+ expect(updateSortClause('', 'First Name', false, 'asc', 'postgres')).toBe(
+ '"First Name" ASC',
+ );
+ expect(updateSortClause('', 'First Name', false, 'asc', 'mysql')).toBe(
+ '`First Name` ASC',
+ );
+ expect(updateSortClause('', 'First Name', false, 'asc', 'mariadb')).toBe(
+ '`First Name` ASC',
+ );
+ expect(updateSortClause('', 'First Name', false, 'asc', 'sqlite')).toBe(
+ '"First Name" ASC',
+ );
+ expect(updateSortClause('', 'First Name', false, 'asc', 'mssql')).toBe(
+ '"First Name" ASC',
+ );
+ });
});
describe('calculateSelectionRange', () => {
diff --git a/packages/web-ui/tests/utils/identifiers.test.ts b/packages/web-ui/tests/utils/identifiers.test.ts
index e6677822a..c807addb7 100644
--- a/packages/web-ui/tests/utils/identifiers.test.ts
+++ b/packages/web-ui/tests/utils/identifiers.test.ts
@@ -241,18 +241,29 @@ describe('formatSqlIdentifier', () => {
expect(formatSqlIdentifier('table-name', 'postgres')).toBe('"table-name"');
});
- it('should leave identifiers unchanged for mysql', () => {
+ it('should leave safe identifiers unchanged and quote unsafe MySQL identifiers', () => {
expect(formatSqlIdentifier('Status', 'mysql')).toBe('Status');
expect(formatSqlIdentifier('user_status', 'mariadb')).toBe('user_status');
expect(formatSqlIdentifier('AccountEventLog', 'mysql')).toBe('AccountEventLog');
- expect(formatSqlIdentifier('select', 'mysql')).toBe('select');
+ expect(formatSqlIdentifier('select', 'mysql')).toBe('`select`');
+ expect(formatSqlIdentifier('First Name', 'mysql')).toBe('`First Name`');
+ expect(formatSqlIdentifier('First Name', 'mariadb')).toBe('`First Name`');
});
- it('should leave identifiers unchanged for sqlite and unknown drivers', () => {
+ it('should preserve safe SQLite identifiers and quote names that require it', () => {
expect(formatSqlIdentifier('Status', 'sqlite')).toBe('Status');
expect(formatSqlIdentifier('Status', null)).toBe('Status');
expect(formatSqlIdentifier('users', 'sqlite')).toBe('users');
expect(formatSqlIdentifier('AccountEventLog', 'sqlite')).toBe('AccountEventLog');
+ expect(formatSqlIdentifier('First Name', 'sqlite')).toBe('"First Name"');
+ expect(formatSqlIdentifier('First Name', null)).toBe('"First Name"');
+ });
+
+ it('uses configured SQL Server brackets and escapes closing brackets', () => {
+ const sqlServer = pluginManifest({identifier_quote: '[', sql_dialect: 'mssql'});
+
+ expect(formatSqlIdentifier('First Name', sqlServer)).toBe('[First Name]');
+ expect(formatSqlIdentifier('First]Name', sqlServer)).toBe('[First]]Name]');
});
it('quotes mixed-case identifiers identically for a "postgresql" plugin manifest and the bare "postgres" string', () => {
expect(formatSqlIdentifier('AccountEventLog', pluginManifest())).toBe(