World's most powerful open data catalog for building a high-performance, geo-distributed and federated metadata lake.
Java ai-catalogdata-catalogdatalakefederated-querylakehousemetadatametalakemodel-catalogopendatacatalogskycomputingstratosphere
[#11547] feat(web-v2): Support Column Metadata Visibility and Editing (#14917)
Ayush tiwari65a63fb5f590
diff --git a/web-v2/integration-test/src/test/java/org/apache/gravitino/integration/test/web/ui/CatalogsPageTest.java b/web-v2/integration-test/src/test/java/org/apache/gravitino/integration/test/web/ui/CatalogsPageTest.javaindex 193122334e..6bb271ee6d 100644--- a/web-v2/integration-test/src/test/java/org/apache/gravitino/integration/test/web/ui/CatalogsPageTest.java+++ b/web-v2/integration-test/src/test/java/org/apache/gravitino/integration/test/web/ui/CatalogsPageTest.java@@ -22,6 +22,7 @@ package org.apache.gravitino.integration.test.web.ui;import static org.apache.gravitino.rel.expressions.transforms.Transforms.identity;import com.google.common.collect.Maps;+import java.time.Duration;import java.util.Arrays;import java.util.List;import java.util.Map;@@ -36,6 +37,7 @@ import org.apache.gravitino.integration.test.web.ui.pages.CatalogsPage;import org.apache.gravitino.integration.test.web.ui.pages.MetalakePage;import org.apache.gravitino.integration.test.web.ui.utils.BaseWebIT;import org.apache.gravitino.rel.Column;+import org.apache.gravitino.rel.TableCatalog;import org.apache.gravitino.rel.expressions.NamedReference;import org.apache.gravitino.rel.expressions.distributions.Distribution;import org.apache.gravitino.rel.expressions.distributions.Distributions;@@ -44,7 +46,11 @@ import org.apache.gravitino.rel.expressions.sorts.SortDirection;import org.apache.gravitino.rel.expressions.sorts.SortOrder;import org.apache.gravitino.rel.expressions.sorts.SortOrders;import org.apache.gravitino.rel.expressions.transforms.Transform;+import org.apache.gravitino.rel.expressions.transforms.Transforms;+import org.apache.gravitino.rel.indexes.Index;+import org.apache.gravitino.rel.indexes.Indexes;import org.apache.gravitino.rel.types.Types;+import org.apache.gravitino.utils.RandomNameUtils;import org.awaitility.Awaitility;import org.junit.jupiter.api.AfterAll;import org.junit.jupiter.api.Assertions;@@ -55,6 +61,9 @@ import org.junit.jupiter.api.Tag;import org.junit.jupiter.api.Test;import org.junit.jupiter.api.TestMethodOrder;import org.openqa.selenium.By;+import org.openqa.selenium.Keys;+import org.openqa.selenium.support.ui.ExpectedConditions;+import org.openqa.selenium.support.ui.WebDriverWait;@Tag("gravitino-docker-test")@TestMethodOrder(MethodOrderer.OrderAnnotation.class)@@ -444,6 +453,22 @@ public class CatalogsPageTest extends BaseWebIT {TABLE_NAME);Assertions.assertTrue(catalogsPage.verifyShowTableTitle(TABLE_TABLE_TITLE));Assertions.assertTrue(catalogsPage.verifyTableColumns());+ List<String> metadataColumns =+ Arrays.asList("Nullable", "AutoIncrement", "Default Value", "Comment");++ catalogsPage.clickColumnSettings();++ for (String column : metadataColumns) {+ catalogsPage.toggleMetadataColumn(column);+ Assertions.assertTrue(+ catalogsPage.verifyTableColumnVisibility(column, false), column + " should be hidden");+ }++ for (String column : metadataColumns) {+ catalogsPage.toggleMetadataColumn(column);+ Assertions.assertTrue(+ catalogsPage.verifyTableColumnVisibility(column, true), column + " should be visible");+ }Assertions.assertTrue(catalogsPage.verifyShowDataItemInList(COLUMN_NAME, true));Assertions.assertTrue(catalogsPage.verifySelectedNode(TABLE_NAME));}@@ -608,6 +633,7 @@ public class CatalogsPageTest extends BaseWebIT {@Test@Order(21)public void testCreateFilesetSchema() throws InterruptedException {+ String schemaComment = "fileset schema comment";// Switch to fileset tab firstcatalogsPage.clickSelectType("fileset");Thread.sleep(1000); // Wait for tab switch@@ -619,11 +645,19 @@ public class CatalogsPageTest extends BaseWebIT {// 2. click create schema buttonclickAndWait(catalogsPage.createSchemaBtn);catalogsPage.setSchemaNameField(SCHEMA_NAME_FILESET);- catalogsPage.setCatalogCommentField("fileset schema comment");+ catalogsPage.setSchemaCommentField(schemaComment);clickAndWait(catalogsPage.handleSubmitSchemaBtn);// 3. verify show table title、 schema name and tree nodeAssertions.assertTrue(catalogsPage.verifyShowTableTitle(CATALOG_TABLE_TITLE));Assertions.assertTrue(catalogsPage.verifyShowDataItemInList(SCHEMA_NAME_FILESET, false));+ Assertions.assertEquals(+ schemaComment,+ gravitinoClient+ .loadMetalake(METALAKE_NAME)+ .loadCatalog(FILESET_CATALOG_NAME)+ .asSchemas()+ .loadSchema(SCHEMA_NAME_FILESET)+ .comment());// Tree view only shows catalogs of current type (fileset)List<String> treeNodes = Arrays.asList(FILESET_CATALOG_NAME, SCHEMA_NAME_FILESET);Assertions.assertTrue(catalogsPage.verifyTreeNodes(treeNodes));@@ -674,4 +708,95 @@ public class CatalogsPageTest extends BaseWebIT {clickAndWait(catalogsPage.backHomeBtn);Assertions.assertTrue(catalogsPage.verifyBackHomePage());}++ @Test+ @Order(24)+ void testMysqlAutoIncrementAndColumnEditsRequireSeparateSaves() throws InterruptedException {+ String schema = RandomNameUtils.genRandomName("auto_increment");+ String table = "users";+ String originalComment = "Original comment";+ String newComment = "Updated comment";+ NameIdentifier tableIdent = NameIdentifier.of(schema, table);+ Catalog catalog = gravitinoClient.loadMetalake(METALAKE_NAME).loadCatalog(MYSQL_CATALOG_NAME);+ TableCatalog tables = catalog.asTableCatalog();+ catalog.asSchemas().createSchema(schema, "", Map.of());+ try {+ tables.createTable(+ tableIdent,+ new Column[] {+ Column.of("id", Types.IntegerType.get(), originalComment, false, true, null)+ },+ "",+ Map.of(),+ Transforms.EMPTY_TRANSFORM,+ Distributions.NONE,+ new SortOrder[0],+ new Index[] {Indexes.createMysqlPrimaryKey(new String[][] {{"id"}})});+ driver.get(+ String.format(+ "%s/ui/catalogs?metalake=%s&catalog=%s&catalogType=%s&schema=%s&table=%s",+ gravitinoUri,+ METALAKE_NAME,+ MYSQL_CATALOG_NAME,+ CATALOG_TYPE_RELATIONAL,+ schema,+ table));++ By editTable = By.cssSelector("[data-refer='edit-table-btn']");+ By autoIncrement = By.id("tableForm_columns_0_autoIncrement");+ By columnComment = By.id("tableForm_columns_0_comment");+ By warningTitle = By.cssSelector(".ant-modal-confirm-title");+ By warningOk =+ By.xpath(+ "//div[contains(@class, 'ant-modal-confirm-warning')]//button[normalize-space(.)='OK']");+ WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(MAX_TIMEOUT));+ clickAndWait(editTable);+ wait.until(ExpectedConditions.attributeToBe(autoIncrement, "aria-checked", "true"));+ clickAndWait(autoIncrement);+ driver.findElement(columnComment).sendKeys(Keys.chord(Keys.CONTROL, "a"), newComment);+ clickAndWait(catalogsPage.handleSubmitTableBtn);+ wait.until(+ ExpectedConditions.textToBePresentInElementLocated(+ warningTitle, "Save these changes separately"));+ Column unchanged = tables.loadTable(tableIdent).columns()[0];+ Assertions.assertTrue(unchanged.autoIncrement());+ Assertions.assertEquals(originalComment, unchanged.comment());+ clickAndWait(warningOk);++ driver.findElement(columnComment).sendKeys(Keys.chord(Keys.CONTROL, "a"), originalComment);+ catalogsPage.selectTableColumnType(0, "long");+ clickAndWait(catalogsPage.handleSubmitTableBtn);+ wait.until(+ ExpectedConditions.textToBePresentInElementLocated(+ warningTitle, "Save these changes separately"));+ Column blocked = tables.loadTable(tableIdent).columns()[0];+ Assertions.assertTrue(blocked.autoIncrement());+ Assertions.assertEquals(Types.IntegerType.get(), blocked.dataType());+ clickAndWait(warningOk);++ catalogsPage.selectTableColumnType(0, "integer");+ clickAndWait(catalogsPage.handleSubmitTableBtn);+ wait.until(ExpectedConditions.invisibilityOfElementLocated(columnComment));++ clickAndWait(editTable);+ wait.until(ExpectedConditions.attributeToBe(autoIncrement, "aria-checked", "false"));+ catalogsPage.selectTableColumnType(0, "long");+ clickAndWait(catalogsPage.handleSubmitTableBtn);+ wait.until(ExpectedConditions.invisibilityOfElementLocated(columnComment));+ Column retyped = tables.loadTable(tableIdent).columns()[0];+ Assertions.assertFalse(retyped.autoIncrement());+ Assertions.assertEquals(Types.LongType.get(), retyped.dataType());++ clickAndWait(editTable);+ wait.until(ExpectedConditions.attributeToBe(autoIncrement, "aria-checked", "false"));+ driver.findElement(columnComment).sendKeys(Keys.chord(Keys.CONTROL, "a"), newComment);+ clickAndWait(catalogsPage.handleSubmitTableBtn);+ wait.until(ExpectedConditions.invisibilityOfElementLocated(columnComment));+ Column saved = tables.loadTable(tableIdent).columns()[0];+ Assertions.assertFalse(saved.autoIncrement());+ Assertions.assertEquals(newComment, saved.comment());+ } finally {+ catalog.asSchemas().dropSchema(schema, true);+ }+ }}diff --git a/web-v2/integration-test/src/test/java/org/apache/gravitino/integration/test/web/ui/pages/CatalogsPage.java b/web-v2/integration-test/src/test/java/org/apache/gravitino/integration/test/web/ui/pages/CatalogsPage.javaindex ccffb5c782..44d74aab45 100644--- a/web-v2/integration-test/src/test/java/org/apache/gravitino/integration/test/web/ui/pages/CatalogsPage.java+++ b/web-v2/integration-test/src/test/java/org/apache/gravitino/integration/test/web/ui/pages/CatalogsPage.java@@ -25,8 +25,10 @@ import static org.apache.gravitino.integration.test.web.ui.CatalogsPageTest.SORTimport java.time.Duration;import java.util.ArrayList;import java.util.Arrays;+import java.util.HashSet;import java.util.List;import java.util.Objects;+import java.util.Set;import org.apache.gravitino.integration.test.web.ui.utils.BaseWebIT;import org.openqa.selenium.By;import org.openqa.selenium.JavascriptExecutor;@@ -165,7 +167,7 @@ public class CatalogsPage extends BaseWebIT {@FindBy(xpath = "//*[@data-refer='metalake-name-link']")public WebElement metalakeNameLink;- @FindBy(xpath = "//thead[contains(@class, 'ant-table-thead')]//tr")+ @FindBy(css = "[data-refer='table-grid'] thead.ant-table-thead > tr")public WebElement columnHeaders;@FindBy(xpath = "//*[@data-refer='metalake-page-title']")@@ -515,29 +517,47 @@ public class CatalogsPage extends BaseWebIT {String columnName = "//div[@data-refer='column-name-" + index + "']//input";WebElement keyInput = driver.findElement(By.xpath(columnName));keyInput.sendKeys(name);- // Set the indexed column type - Ant Design Select structure- String columnType = "//div[@data-refer='column-type-" + index + "']";- WebElement typeSelect = driver.findElement(By.xpath(columnType));- clickAndWait(typeSelect);- // Wait for dropdown to appear and click the option- // Ant Design Select dropdown - try multiple selectors for compatibility- Thread.sleep(500);- WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(MAX_TIMEOUT));- String optionXpath =- "//div[contains(@class, 'ant-select-dropdown')]"- + "//div[contains(@class, 'ant-select-item-option') and (@title='"- + type- + "' or .//div[text()='"- + capitalizeFirstLetter(type)- + "'])]";- WebElement typeItem =- wait.until(ExpectedConditions.elementToBeClickable(By.xpath(optionXpath)));- clickAndWait(typeItem);++ selectTableColumnType(index, type);} catch (Exception e) {LOG.error(e.getMessage(), e);}}+ /**+ * Selects the data type of a column in the table editor.+ *+ * @param index zero-based column index+ * @param type the type to select+ * @throws InterruptedException if interrupted while interacting with the editor+ */+ public void selectTableColumnType(int index, String type) throws InterruptedException {+ String columnType = "[data-refer='column-type-" + index + "']";+ clickAndWait(By.cssSelector(columnType + " .ant-select-selector"));+ WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(MAX_TIMEOUT));+ WebElement combobox = driver.findElement(By.cssSelector(columnType + " [role='combobox']"));+ wait.until(ExpectedConditions.attributeToBe(combobox, "aria-expanded", "true"));++ // The dropdown renders only a window of options. Keyboard navigation brings each into view.+ Set<String> visited = new HashSet<>();+ String activeOption = wait.until(ignored -> combobox.getDomAttribute("aria-activedescendant"));+ while (activeOption != null && visited.add(activeOption)) {+ String activeType = driver.findElement(By.id(activeOption)).getDomProperty("textContent");+ if (type.equalsIgnoreCase(activeType)) {+ combobox.sendKeys(Keys.ENTER);+ wait.until(ExpectedConditions.attributeToBe(combobox, "aria-expanded", "false"));+ wait.until(+ ExpectedConditions.textToBe(+ By.cssSelector(columnType + " .ant-select-selection-item"),+ capitalizeFirstLetter(type)));+ return;+ }+ combobox.sendKeys(Keys.ARROW_DOWN);+ activeOption = combobox.getDomAttribute("aria-activedescendant");+ }+ throw new IllegalStateException("Column type option is unavailable: " + type);+ }+private String capitalizeFirstLetter(String str) {if (str == null || str.isEmpty()) {return str;@@ -1237,7 +1257,7 @@ public class CatalogsPage extends BaseWebIT {}/**- * Click the table overview link to open the popover.+ * Click the table overview link to open the popover. 0** @param linkType The type of link to click (properties, partitions, sortorders, distribution,* indexes).@@ -1392,53 +1412,23 @@ public class CatalogsPage extends BaseWebIT {public boolean verifyTableColumns() {try {- List<String> columns = Arrays.asList("Column Name", "Data Type", "Tags");-- // Ant Design Table structure: thead > tr > th- List<WebElement> columnHeadersRows =- columnHeaders.findElements(By.xpath("./th[contains(@class, 'ant-table-cell')]"));- // Filter out header cells that have no visible text (selection/expand columns)- List<String> headerTexts = new ArrayList<>();- for (WebElement th : columnHeadersRows) {- String txt = th.getText() == null ? "" : th.getText().trim();- boolean hasInteractiveChild = false;- try {- // if header contains inputs/icons/buttons and no text, treat as non-data header- List<WebElement> interactive =- th.findElements(By.xpath(".//input|.//button|.//svg|.//i"));- if (interactive != null && !interactive.isEmpty()) {- hasInteractiveChild = true;- }- } catch (Exception e) {- LOG.debug("Error checking interactive children of header: {}", e.getMessage());- }-- if (!txt.isEmpty()) {- headerTexts.add(txt);- } else if (!hasInteractiveChild) {- // If there is no interactive child but text is empty, still skip it- // (some UIs render invisible helper headers)- continue;- }- }-- if (headerTexts.size() != columns.size()) {- LOG.error(- "Column headers count does not match after filtering, expected: {}, actual: {} -> {}",- columns.size(),- headerTexts.size(),- headerTexts);+ List<String> columns =+ Arrays.asList(+ "Column Name",+ "Data Type",+ "Tags",+ "Policies",+ "Nullable",+ "AutoIncrement",+ "Default Value",+ "Comment");++ List<String> headerTexts = getTableColumnNames();+ if (!columns.equals(headerTexts)) {+ LOG.error("Column headers do not match, expected: {}, actual: {}", columns, headerTexts);return false;}- for (int i = 0; i < columns.size(); i++) {- String headerText = headerTexts.get(i);- if (!headerText.equals(columns.get(i))) {- LOG.error("Column header '{}' does not match, expected '{}'", headerText, columns.get(i));- return false;- }- }-return true;} catch (Exception e) {LOG.error(e.getMessage(), e);@@ -1446,6 +1436,48 @@ public class CatalogsPage extends BaseWebIT {}}+ public void clickColumnSettings() {+ WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(MAX_TIMEOUT));++ WebElement settingsButton =+ wait.until(+ ExpectedConditions.elementToBeClickable(+ By.xpath("//button[@aria-label='Column settings']")));++ try {+ clickAndWait(settingsButton);+ } catch (InterruptedException e) {+ Thread.currentThread().interrupt();+ throw new RuntimeException("Interrupted while opening column settings", e);+ }+ }++ public void toggleMetadataColumn(String columnName) {+ String xpath =+ "//div[contains(@class, 'ant-popover') and not(contains(@class, 'ant-popover-hidden'))]"+ + "//label[contains(@class, 'ant-checkbox-wrapper') and normalize-space(.)='"+ + columnName+ + "']";++ WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(MAX_TIMEOUT));++ WebElement checkbox = wait.until(ExpectedConditions.elementToBeClickable(By.xpath(xpath)));++ checkbox.click();+ }++ public boolean verifyTableColumnVisibility(String columnName, boolean expectedVisible) {+ try {+ WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(MAX_TIMEOUT));++ return wait.ignoring(StaleElementReferenceException.class)+ .until(currentDriver -> getTableColumnNames().contains(columnName) == expectedVisible);+ } catch (Exception e) {+ LOG.error("Failed to verify column visibility: {}", columnName, e);+ return false;+ }+ }+public boolean verifyTableProperties(String type, String colName) {try {String xpath = "";@@ -1677,4 +1709,16 @@ public class CatalogsPage extends BaseWebIT {}return true;}++ private List<String> getTableColumnNames() {+ List<String> names = new ArrayList<>();+ for (WebElement header : columnHeaders.findElements(By.cssSelector("th.ant-table-cell"))) {+ // getText() can omit headers clipped by the horizontal scroll container.+ String name = Objects.toString(header.getDomProperty("textContent"), "").trim();+ if (!name.isEmpty()) {+ names.add(name);+ }+ }+ return names;+ }}diff --git a/web-v2/web/src/app/catalogs/rightContent/CreateTableDialog.js b/web-v2/web/src/app/catalogs/rightContent/CreateTableDialog.jsindex 406989bf65..4f3a9506ab 100644--- a/web-v2/web/src/app/catalogs/rightContent/CreateTableDialog.js+++ b/web-v2/web/src/app/catalogs/rightContent/CreateTableDialog.js@@ -53,7 +53,6 @@ import {ColumnSpesicalType,ColumnType,ColumnTypeForUnsigned,- ColumnTypeSupportAutoIncrement,ColumnWithParamType,UnsupportColumnType,autoIncrementInfoMap,@@ -68,7 +67,13 @@ import {} from '@/config'import { tableDefaultProps } from '@/config/catalog'import { nameRegex } from '@/lib/utils/regex'-import { capitalizeFirstLetter, genUpdates } from '@/lib/utils'+import {+ capitalizeFirstLetter,+ genUpdates,+ normalizeColumnDefaultValue,+ isAutoIncrementColumnTypeSupported,+ hasAutoIncrementEditConflict+} from '@/lib/utils'import { cn } from '@/lib/utils/tailwind'import { createTable, updateTable, getTableDetails } from '@/lib/store/metalakes'import { useAppDispatch } from '@/lib/hooks/useStore'@@ -420,8 +425,15 @@ export default function CreateTableDialog({ ...props }) {)}}- if (table.columns[key].defaultValue) {- form.setFieldValue(['columns', key, 'defaultValue'], table.columns[key].defaultValue)+ const defaultValue = table.columns[key].defaultValue++ if (defaultValue) {+ form.setFieldValue(+ ['columns', key, 'defaultValue'],+ defaultValue.type === 'unparsed'+ ? { ...defaultValue, value: defaultValue.unparsedExpression }+ : defaultValue+ )}}if (table.distribution) {@@ -597,6 +609,16 @@ export default function CreateTableDialog({ ...props }) {form.validateFields().then(async () => {+ if (editTable && hasAutoIncrementEditConflict(provider, cacheData?.columns, values?.columns)) {+ Modal.warning({+ title: 'Save these changes separately',+ content:+ 'When turning AutoIncrement off, save it first. When turning it on, save it last. Reopen the table and apply one change per save.'+ })++ return+ }+setConfirmLoading(true)let submitted = false@@ -620,39 +642,7 @@ export default function CreateTableDialog({ ...props }) {column['autoIncrement'] = col.autoIncrement}if (col.defaultValue) {- switch (col.defaultValue.type) {- case 'field':- column['defaultValue'] = {- type: 'field',- fieldName: [col.defaultValue?.fieldName]- }- break- case 'function':- column['defaultValue'] = {- type: 'function',- funcName: col.defaultValue?.funcName,- funcArgs: col.defaultValue?.funcArgs.map(f => {- const func = {}- if (f.type === 'literal') {- func['type'] = 'literal'- func['dataType'] = 'string'- func['value'] = f.value- } else {- func['type'] = 'field'- func['fieldName'] = [f.fieldName]- }-- return func- })- }- break- default:- column['defaultValue'] = {- type: 'literal',- dataType: col.defaultValue?.dataType || 'string',- value: col.defaultValue?.value- }- }+ column['defaultValue'] = normalizeColumnDefaultValue(col.defaultValue)}return column@@ -962,10 +952,7 @@ export default function CreateTableDialog({ ...props }) {><Switchsize='small'- disabled={- !!editTable ||- !ColumnTypeSupportAutoIncrement.includes(values?.columns[subField.name]?.typeObj?.type)- }+ disabled={!isAutoIncrementColumnTypeSupported(values?.columns?.[subField.name]?.typeObj?.type)}/></Form.Item><Form.Itemdiff --git a/web-v2/web/src/app/catalogs/rightContent/entitiesContent/TableDetailsPage.js b/web-v2/web/src/app/catalogs/rightContent/entitiesContent/TableDetailsPage.jsindex f580421672..20d4d21e7a 100644--- a/web-v2/web/src/app/catalogs/rightContent/entitiesContent/TableDetailsPage.js+++ b/web-v2/web/src/app/catalogs/rightContent/entitiesContent/TableDetailsPage.js@@ -21,7 +21,7 @@import { useMemo, useState, useEffect } from 'react'import dynamic from 'next/dynamic'-import { Divider, Flex, Input, Popover, Space, Spin, Table, Tabs, Tag, Tooltip, Typography } from 'antd'+import { Checkbox, Divider, Flex, Input, Popover, Space, Spin, Table, Tabs, Tag, Tooltip, Typography } from 'antd'import { useAntdColumnResize } from 'react-antd-column-resize'import useResizeObserver from 'use-resize-observer'import AssociatedTable from '@/components/AssociatedTable'@@ -46,6 +46,42 @@ const SetOwnerDialog = dynamic(() => import('@/components/SetOwnerDialog'), {const { Title, Paragraph } = Typographyconst { Search } = Input+const formatColumnDefaultValue = defaultValue => {+ const formatExpression = expression => {+ if (!expression || typeof expression !== 'object') return ''++ switch (expression.type) {+ case 'literal':+ if (expression.dataType === 'null' || expression.value == null) return 'NULL'++ return expression.value === '' ? "''" : String(expression.value)++ case 'field': {+ const fieldName = expression.fieldName++ return Array.isArray(fieldName) ? fieldName.join('.') : String(fieldName || '')+ }++ case 'function': {+ const functionName = expression.functionName || expression.funcName+ const args = expression.functionArgs || expression.funcArgs || []++ if (!functionName) return ''++ return `${functionName}(${args.map(formatExpression).join(', ')})`+ }++ case 'unparsed':+ return expression.unparsedExpression || ''++ default:+ return expression.value == null ? '' : String(expression.value)+ }+ }++ return formatExpression(defaultValue) || '-'+}+export default function TableDetailsPage({ ...props }) {const [open, setOpen] = useState(false)const [openOwner, setOpenOwner] = useState(false)@@ -58,6 +94,13 @@ export default function TableDetailsPage({ ...props }) {const currentMetalake = searchParams.get('metalake')const catalogType = searchParams.get('catalogType')const [search, setSearch] = useState('')++ const [visibleMetadataColumns, setVisibleMetadataColumns] = useState([+ 'nullable',+ 'autoIncrement',+ 'defaultValue',+ 'comment'+ ])const [tabKey, setTabKey] = useState('Columns')const { ref, width } = useResizeObserver()const store = useAppSelector(state => state.metalakes)@@ -363,57 +406,99 @@ export default function TableDetailsPage({ ...props }) {}const columns = useMemo(- () => [- {- title: 'Column Name',- dataIndex: 'name',- key: 'name',- width: 300,- ellipsis: true,- sort: (a, b) => a.name.toLowerCase().localeCompare(b.name.toLowerCase()),- render: name => (- <Space>- <span>{name}</span>- {partitioning && renderColumnPopover('Partitioning', 'tabler:circle-letter-p', partitioning, name)}- {sortOrders && renderColumnPopover('SortOrders', 'mdi:letter-s-circle-outline', sortOrders, name)}- {distribution && renderColumnPopover('Distribution', 'tabler:circle-letter-d', distribution, name)}- {indexes && renderColumnPopover('Indexes', 'mdi:letter-i-circle-outline', indexes, name, true)}- </Space>- )- },- {- title: 'Data Type',- dataIndex: 'type',- key: 'type',- width: 200,- ellipsis: true,- filters: columnTypeFitlers,- onFilter: (value, record) =>- typeof record.type === 'string' ? record.type.indexOf(value) === 0 : record.type.type.indexOf(value) === 0,- render: type => {- const formattedType = formatColumnType(type)-- return (- <Tag color={columnTypeColor(type)} title={formattedType}>- {formattedType}- </Tag>+ () =>+ [+ {+ title: 'Column Name',+ dataIndex: 'name',+ key: 'name',+ width: 300,+ ellipsis: true,+ sort: (a, b) => a.name.toLowerCase().localeCompare(b.name.toLowerCase()),+ render: name => (+ <Space>+ <span>{name}</span>+ {partitioning && renderColumnPopover('Partitioning', 'tabler:circle-letter-p', partitioning, name)}+ {sortOrders && renderColumnPopover('SortOrders', 'mdi:letter-s-circle-outline', sortOrders, name)}+ {distribution && renderColumnPopover('Distribution', 'tabler:circle-letter-d', distribution, name)}+ {indexes && renderColumnPopover('Indexes', 'mdi:letter-i-circle-outline', indexes, name, true)}+ </Space>)+ },+ {+ title: 'Data Type',+ dataIndex: 'type',+ key: 'type',+ width: 200,+ ellipsis: true,+ filters: columnTypeFitlers,+ onFilter: (value, record) =>+ typeof record.type === 'string' ? record.type.indexOf(value) === 0 : record.type.type.indexOf(value) === 0,+ render: type => {+ const formattedType = formatColumnType(type)++ return (+ <Tag color={columnTypeColor(type)} title={formattedType}>+ {formattedType}+ </Tag>+ )+ }+ },+ {+ title: 'Tags',+ dataIndex: 'tags',+ key: 'tags',+ render: (_, record) =>+ record?.node === 'tableColumn' ? (+ <Tags+ metadataObjectType={'column'}+ metadataObjectFullName={`${catalog}.${schema}.${table}.${record.name}`}+ />+ ) : null+ },+ {+ title: 'Policies',+ dataIndex: 'policies',+ key: 'policies',+ render: (_, record) =>+ record?.node === 'tableColumn' ? (+ <Policies+ metadataObjectType={'column'}+ metadataObjectFullName={`${catalog}.${schema}.${table}.${record.name}`}+ />+ ) : null+ },+ {+ title: 'Nullable',+ dataIndex: 'nullable',+ key: 'nullable',+ metadataKey: 'nullable',+ render: value => (value ? 'Yes' : 'No')+ },+ {+ title: 'AutoIncrement',+ dataIndex: 'autoIncrement',+ key: 'autoIncrement',+ metadataKey: 'autoIncrement',+ render: value => (value ? 'Yes' : 'No')+ },+ {+ title: 'Default Value',+ dataIndex: 'defaultValue',+ key: 'defaultValue',+ metadataKey: 'defaultValue',+ render: formatColumnDefaultValue+ },+ {+ title: 'Comment',+ dataIndex: 'comment',+ key: 'comment',+ metadataKey: 'comment',+ ellipsis: true,+ render: value => value || '-'}- },- {- title: 'Tags',- dataIndex: 'tags',- key: 'tags',- render: (_, record) =>- record?.node === 'tableColumn' ? (- <Tags- metadataObjectType={'column'}- metadataObjectFullName={`${catalog}.${schema}.${table}.${record.name}`}- />- ) : null- }- ],- [store.activatedDetails]+ ].filter(column => !column.metadataKey || visibleMetadataColumns.includes(column.metadataKey)),+ [store.activatedDetails, visibleMetadataColumns])const { resizableColumns, components, tableWidth } = useAntdColumnResize(() => {@@ -439,6 +524,7 @@ export default function TableDetailsPage({ ...props }) {</span><Tooltip title='Edit'><Icons.Pencil+ data-refer='edit-table-btn'className='relative size-4 hover:cursor-pointer hover:text-defaultPrimary'onClick={handleEditTable}/>@@ -591,10 +677,38 @@ export default function TableDetailsPage({ ...props }) {<Tabs data-refer='details-tabs' defaultActiveKey={tabKey} onChange={onChangeTab} items={tabOptions} />{tabKey === 'Columns' && (<>- <Flex justify='flex-end' className='mb-4'>+ <Flex justify='flex-end' align='center' gap='middle' className='mb-4'><div className='flex w-1/3 gap-4'><Search name='searcColumnInput' placeholder='Search...' value={search} onChange={onSearchTable} /></div>++ <Popover+ trigger='click'+ placement='bottomRight'+ title='Column settings'+ content={+ <Checkbox.Group+ className='flex flex-col gap-2'+ options={[+ { label: 'Nullable', value: 'nullable' },+ { label: 'AutoIncrement', value: 'autoIncrement' },+ { label: 'Default Value', value: 'defaultValue' },+ { label: 'Comment', value: 'comment' }+ ]}+ value={visibleMetadataColumns}+ onChange={setVisibleMetadataColumns}+ />+ }+ >+ <button+ type='button'+ aria-label='Column settings'+ title='Column settings'+ className='cursor-pointer border-0 bg-transparent p-0 hover:text-defaultPrimary focus-visible:outline focus-visible:outline-2 focus-visible:outline-offset-2'+ >+ <Icons.Settings className='size-4' />+ </button>+ </Popover></Flex><Spin spinning={store.activatedDetailsLoading}><Tablediff --git a/web-v2/web/src/app/catalogs/rightContent/entitiesContent/TableDetailsPage.test.jsx b/web-v2/web/src/app/catalogs/rightContent/entitiesContent/TableDetailsPage.test.jsxnew file mode 100644index 0000000000..ac3538c537--- /dev/null+++ b/web-v2/web/src/app/catalogs/rightContent/entitiesContent/TableDetailsPage.test.jsx@@ -0,0 +1,144 @@+/*+ * Licensed to the Apache Software Foundation (ASF) under one+ * or more contributor license agreements. See the NOTICE file+ * distributed with this work for additional information+ * regarding copyright ownership. The ASF licenses this file+ * to you under the Apache License, Version 2.0 (the+ * "License"); you may not use this file except in compliance+ * with the License. You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing,+ * software distributed under the License is distributed on an+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY+ * KIND, either express or implied. See the License for the+ * specific language governing permissions and limitations+ * under the License.+ */++import { act } from 'react'+import { createRoot } from 'react-dom/client'+import { Provider } from 'react-redux'+import { configureStore } from '@reduxjs/toolkit'+import { afterEach, beforeEach, expect, it, vi } from 'vitest'+import reducer, { getTableDetails } from '@/lib/store/metalakes'+import { defHttp } from '@/lib/utils/axios'+import TableDetailsPage from './TableDetailsPage'++const namespaces = { metalake: 'demo', catalog: 'sales', schema: 'mart', table: 'orders' }++vi.mock('next/navigation', () => ({+ useSearchParams: () => new URLSearchParams({ ...namespaces, catalogType: 'relational' }),+ useRouter: () => ({ push: vi.fn() })+}))+vi.mock('@/lib/utils/axios', () => ({ defHttp: { get: vi.fn() } }))+vi.mock('@/components/CustomTags', () => ({ default: () => null }))+vi.mock('@/components/PolicyTag', () => ({ default: () => null }))+vi.mock('../CreateTableDialog', () => ({ default: () => null }))++let container+let root+let store++beforeEach(() => {+ vi.stubGlobal('IS_REACT_ACT_ENVIRONMENT', true)+ const getComputedStyle = window.getComputedStyle+ vi.spyOn(window, 'getComputedStyle').mockImplementation(element => getComputedStyle(element))+ vi.stubGlobal(+ 'ResizeObserver',+ class {+ observe() {}+ unobserve() {}+ disconnect() {}+ }+ )+ vi.stubGlobal(+ 'matchMedia',+ vi.fn(() => ({ matches: false, addListener() {}, removeListener() {} }))+ )+ store = configureStore({ reducer: { metalakes: reducer, auth: () => ({ anthEnable: false }) } })+ container = document.createElement('div')+ document.body.appendChild(container)+ root = createRoot(container)+})++afterEach(async () => {+ await act(async () => root.unmount())+ container.remove()+ vi.restoreAllMocks()+ vi.unstubAllGlobals()+})++async function renderTable(columns) {+ const table = { name: 'orders', columns, distribution: { strategy: 'none', funcArgs: [] } }+ defHttp.get.mockImplementation(({ url }) =>+ Promise.resolve(url.endsWith('/tables/orders') ? { table } : { catalog: { name: 'sales' } })+ )+ await store.dispatch(getTableDetails({ ...namespaces, init: true })).unwrap()+ await act(async () =>+ root.render(+ <Provider store={store}>+ <TableDetailsPage namespaces={namespaces} />+ </Provider>+ )+ )+}++function columnHeaders() {+ return [...container.querySelectorAll('[data-refer="table-grid"] thead th')].map(header => header.textContent.trim())+}++function columnValues(name) {+ const index = columnHeaders().indexOf(name)++ return [...container.querySelectorAll('[data-refer="table-grid"] tbody tr[data-row-key]')].map(+ row => row.cells[index].textContent+ )+}++it('shows table column metadata and lets users hide and restore each column', async () => {+ await renderTable([+ { name: 'id', type: 'long', nullable: false, autoIncrement: true, comment: 'Order ID' },+ {+ name: 'created_at',+ type: 'timestamp',+ nullable: true,+ autoIncrement: false,+ defaultValue: { type: 'function', funcName: 'current_timestamp', funcArgs: [] }+ }+ ])++ const metadata = {+ Nullable: ['No', 'Yes'],+ AutoIncrement: ['Yes', 'No'],+ 'Default Value': ['-', 'current_timestamp()'],+ Comment: ['Order ID', '-']+ }+ const headers = ['Column Name', 'Data Type', 'Tags', 'Policies', ...Object.keys(metadata)]+ expect(columnHeaders()).toEqual(headers)++ await act(async () => container.querySelector('button[aria-label="Column settings"]').click())+ for (const [column, values] of Object.entries(metadata)) {+ const checkbox = [...document.querySelectorAll('label')].find(label => label.textContent === column).control+ expect(checkbox.checked).toBe(true)+ expect(columnValues(column)).toEqual(values)++ await act(async () => checkbox.click())+ expect(columnHeaders()).toEqual(headers.filter(header => header !== column))++ await act(async () => checkbox.click())+ expect(columnHeaders()).toEqual(headers)+ expect(columnValues(column)).toEqual(values)+ }+}, 15000)++it('distinguishes empty string and explicit NULL defaults from a missing default', async () => {+ await renderTable([+ { name: 'empty', type: 'string', defaultValue: { type: 'literal', dataType: 'string', value: '' } },+ { name: 'explicit_null', type: 'string', defaultValue: { type: 'literal', dataType: 'null', value: 'NULL' } },+ { name: 'missing', type: 'string' }+ ])++ expect(columnValues('Default Value')).toEqual(["''", 'NULL', '-'])+})diff --git a/web-v2/web/src/lib/utils/genUpdates.test.js b/web-v2/web/src/lib/utils/genUpdates.test.jsnew file mode 100644index 0000000000..4991b82978--- /dev/null+++ b/web-v2/web/src/lib/utils/genUpdates.test.js@@ -0,0 +1,393 @@+/*+ * Licensed to the Apache Software Foundation (ASF) under one+ * or more contributor license agreements. See the NOTICE file+ * distributed with this work for additional information+ * regarding copyright ownership. The ASF licenses this file+ * to you under the Apache License, Version 2.0 (the+ * "License"); you may not use this file except in compliance+ * with the License. You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing,+ * software distributed under the License is distributed on an+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY+ * KIND, either express or implied. See the License for the+ * specific language governing permissions and limitations+ * under the License.+ */++import { describe, expect, it } from 'vitest'+import {+ genUpdates,+ normalizeColumnDefaultValue,+ isAutoIncrementColumnTypeSupported,+ hasAutoIncrementEditConflict+} from './index'++const createTableData = (autoIncrement, defaultValue) => ({+ name: 'users',+ columns: [+ {+ uniqueId: 'id',+ name: 'id',+ type: 'long',+ nullable: false,+ autoIncrement,+ comment: '',+ ...(defaultValue !== undefined ? { defaultValue } : {})+ }+ ]+})+describe('genUpdates', () => {+ it.each([+ [false, true],+ [true, false]+ ])('generates auto-increment update when changing from %s to %s', (originalValue, newValue) => {+ const originalData = createTableData(originalValue)+ const newData = createTableData(newValue)++ expect(genUpdates(originalData, newData)).toContainEqual({+ '@type': 'updateColumnAutoIncrement',+ fieldName: ['id'],+ autoIncrement: newValue+ })+ })++ it('does not generate an auto-increment update when the value is unchanged', () => {+ const originalData = createTableData(false)+ const newData = createTableData(false)++ expect(genUpdates(originalData, newData)).toEqual([])+ })++ it('preserves REST function defaults without generating unnecessary updates', () => {+ const defaultValue = {+ type: 'function',+ funcName: 'current_timestamp',+ funcArgs: []+ }++ const normalized = normalizeColumnDefaultValue(defaultValue)++ const originalData = createTableData(false, defaultValue)+ const newData = createTableData(false, normalized)++ expect(normalized).toEqual(defaultValue)+ expect(genUpdates(originalData, newData)).toEqual([])+ })++ it('preserves nested function expressions using REST property names', () => {+ const expression = {+ type: 'function',+ funcName: 'coalesce',+ funcArgs: [+ {+ type: 'field',+ fieldName: ['created_at']+ },+ {+ type: 'function',+ funcName: 'lower',+ funcArgs: [+ {+ type: 'literal',+ dataType: 'string',+ value: 'UNKNOWN'+ }+ ]+ }+ ]+ }++ expect(normalizeColumnDefaultValue(expression)).toEqual(expression)+ })++ it('preserves field default expressions', () => {+ const expression = {+ type: 'field',+ fieldName: ['created_at']+ }++ expect(normalizeColumnDefaultValue(expression)).toEqual(expression)+ })++ it('preserves unparsed default expressions', () => {+ const expression = {+ type: 'unparsed',+ unparsedExpression: 'CURRENT_TIMESTAMP'+ }++ expect(normalizeColumnDefaultValue(expression)).toEqual(expression)+ })++ it('preserves an unparsed default loaded into the edit form unchanged', () => {+ const defaultValue = {+ type: 'unparsed',+ unparsedExpression: 'CURRENT_TIMESTAMP'+ }++ const formValue = {+ ...defaultValue,+ value: defaultValue.unparsedExpression+ }++ const normalized = normalizeColumnDefaultValue(formValue)++ expect(normalized).toEqual(defaultValue)+ expect(genUpdates(createTableData(false, defaultValue), createTableData(false, normalized))).toEqual([])+ })++ it('generates an update when an unparsed default is edited', () => {+ const originalDefault = {+ type: 'unparsed',+ unparsedExpression: 'CURRENT_TIMESTAMP'+ }++ const formValue = {+ ...originalDefault,+ value: 'CURRENT_DATE'+ }++ const newDefault = normalizeColumnDefaultValue(formValue)++ expect(newDefault).toEqual({+ type: 'unparsed',+ unparsedExpression: 'CURRENT_DATE'+ })++ expect(genUpdates(createTableData(false, originalDefault), createTableData(false, newDefault))).toContainEqual({+ '@type': 'updateColumnDefaultValue',+ fieldName: ['id'],+ newDefaultValue: newDefault+ })+ })++ it.each([+ { type: 'literal', dataType: 'string', value: '' },+ { type: 'literal', dataType: 'null', value: 'NULL' }+ ])('can set an explicit default on a column without one (%j)', defaultValue => {+ const column = { uniqueId: 'name', name: 'name', type: 'string', nullable: true }++ expect(genUpdates({ columns: [column] }, { columns: [{ ...column, defaultValue }] })).toEqual([+ { '@type': 'updateColumnDefaultValue', fieldName: ['name'], newDefaultValue: defaultValue }+ ])+ })++ it.each([true, false])('includes autoIncrement when adding a new column: %s', autoIncrement => {+ const originalData = {+ name: 'users',+ columns: []+ }++ const newData = createTableData(autoIncrement)++ expect(genUpdates(originalData, newData)).toContainEqual({+ '@type': 'addColumn',+ fieldName: ['id'],+ type: 'long',+ nullable: false,+ autoIncrement,+ comment: ''+ })+ })++ it.each([undefined, null, '', 'string', 'map'])('safely rejects unsupported or missing column type: %s', type => {+ expect(isAutoIncrementColumnTypeSupported(type)).toBe(false)+ })++ it.each(['long', 'Long', 'LONG', ' Long '])('recognizes supported AutoIncrement type: %s', type => {+ expect(isAutoIncrementColumnTypeSupported(type)).toBe(true)+ })++ it('generates an update when a function default actually changes', () => {+ const originalDefault = {+ type: 'function',+ funcName: 'current_timestamp',+ funcArgs: []+ }++ const newDefault = {+ type: 'function',+ funcName: 'date_trunc',+ funcArgs: [+ {+ type: 'literal',+ dataType: 'string',+ value: 'day'+ }+ ]+ }++ const updates = genUpdates(createTableData(false, originalDefault), createTableData(false, newDefault))++ expect(updates).toContainEqual({+ '@type': 'updateColumnDefaultValue',+ fieldName: ['id'],+ newDefaultValue: newDefault+ })+ })+ it('does not disable AutoIncrement when the field is omitted during an unrelated edit', () => {+ const originalData = createTableData(true)+ const newData = createTableData(false)++ delete newData.columns[0].autoIncrement++ originalData.comment = 'Old comment'+ newData.comment = 'Updated comment'++ expect(genUpdates(originalData, newData)).toEqual([+ {+ '@type': 'updateComment',+ newComment: 'Updated comment'+ }+ ])+ })+})+describe('hasAutoIncrementEditConflict', () => {+ const originalColumn = { uniqueId: 'id', name: 'id', type: 'integer', autoIncrement: true, comment: 'Old comment' }++ it.each(['jdbc-mysql', 'jdbc-oceanbase'])('blocks renaming and disabling AutoIncrement on %s', provider => {+ const newColumn = { ...originalColumn, name: 'user_id', autoIncrement: false }++ expect(hasAutoIncrementEditConflict(provider, [originalColumn], [newColumn])).toBe(true)+ })++ it.each(['jdbc-mysql', 'jdbc-oceanbase'])(+ 'blocks changing the comment and disabling AutoIncrement on %s',+ provider => {+ const newColumn = { ...originalColumn, comment: 'New comment', autoIncrement: false }++ expect(hasAutoIncrementEditConflict(provider, [originalColumn], [newColumn])).toBe(true)+ }+ )++ it('blocks clearing the comment while enabling AutoIncrement', () => {+ const oldColumn = { ...originalColumn, autoIncrement: false }+ const newColumn = { ...originalColumn, comment: '' }++ expect(hasAutoIncrementEditConflict('jdbc-mysql', [oldColumn], [newColumn])).toBe(true)+ })++ describe.each(['jdbc-mysql', 'jdbc-oceanbase'])('default value edits on %s', provider => {+ it('requires disabling AutoIncrement before setting a default', () => {+ const disabled = { ...originalColumn, autoIncrement: false }+ const edited = { ...disabled, defaultValue: { value: '1' } }++ expect(hasAutoIncrementEditConflict(provider, [originalColumn], [edited])).toBe(true)+ expect(hasAutoIncrementEditConflict(provider, [originalColumn], [disabled])).toBe(false)+ expect(hasAutoIncrementEditConflict(provider, [disabled], [edited])).toBe(false)+ })++ it('blocks editing an existing expression while enabling AutoIncrement', () => {+ const defaultValue = { type: 'unparsed', unparsedExpression: '1' }+ const saved = { ...originalColumn, autoIncrement: false, defaultValue }+ const edited = { ...saved, autoIncrement: true, defaultValue: { ...defaultValue, value: '2' } }++ expect(hasAutoIncrementEditConflict(provider, [saved], [edited])).toBe(true)+ })++ it.each([+ [+ { unparsedExpression: '1', type: 'unparsed' },+ { type: 'unparsed', unparsedExpression: '1', value: '1' }+ ],+ [+ { type: 'function', funcName: 'current_timestamp' },+ { type: 'function', funcName: 'current_timestamp', funcArgs: [] }+ ],+ [null, { value: undefined }]+ ])('allows an unchanged default and emits only the AutoIncrement update (%j)', (savedDefault, formDefault) => {+ const saved = createTableData(true, savedDefault)+ const edited = { ...saved.columns[0], autoIncrement: false, defaultValue: formDefault }++ expect(hasAutoIncrementEditConflict(provider, saved.columns, [edited])).toBe(false)+ expect(genUpdates(saved, createTableData(false, normalizeColumnDefaultValue(formDefault)))).toEqual([+ { '@type': 'updateColumnAutoIncrement', fieldName: ['id'], autoIncrement: false }+ ])+ })+ })++ it.each(['jdbc-mysql', 'jdbc-oceanbase'])(+ 'blocks changing Integer to Long and disabling AutoIncrement on %s',+ provider => {+ const newColumn = { ...originalColumn, typeObj: { type: 'Long' }, autoIncrement: false }++ expect(hasAutoIncrementEditConflict(provider, [originalColumn], [newColumn])).toBe(true)+ }+ )++ it('blocks changing the type and enabling AutoIncrement in the same save', () => {+ const oldColumn = { ...originalColumn, type: 'varchar(32)', autoIncrement: false }+ const newColumn = { ...oldColumn, typeObj: { type: 'Long' }, autoIncrement: true }++ expect(hasAutoIncrementEditConflict('jdbc-mysql', [oldColumn], [newColumn])).toBe(true)+ })++ it.each(['jdbc-mysql', 'jdbc-oceanbase'])(+ 'requires saving Required before enabling AutoIncrement on %s',+ provider => {+ const saved = { ...originalColumn, nullable: true, autoIncrement: false }+ const edited = { uniqueId: 'id', name: 'id', comment: saved.comment, required: true, autoIncrement: true }++ expect(hasAutoIncrementEditConflict(provider, [saved], [edited])).toBe(true)+ expect(hasAutoIncrementEditConflict(provider, [saved], [{ ...edited, autoIncrement: false }])).toBe(false)+ expect(hasAutoIncrementEditConflict(provider, [{ ...saved, nullable: false }], [edited])).toBe(false)+ }+ )++ it.each(['jdbc-mysql', 'jdbc-oceanbase'])(+ 'requires disabling AutoIncrement before clearing Required on %s',+ provider => {+ const saved = { ...originalColumn, nullable: false }+ const edited = { uniqueId: 'id', name: 'id', comment: saved.comment, required: false, autoIncrement: false }++ expect(hasAutoIncrementEditConflict(provider, [saved], [edited])).toBe(true)+ expect(hasAutoIncrementEditConflict(provider, [saved], [{ ...edited, required: true }])).toBe(false)+ expect(hasAutoIncrementEditConflict(provider, [{ ...saved, autoIncrement: false }], [edited])).toBe(false)+ }+ )++ it.each([+ { name: 'user_id' },+ { comment: 'New comment' },+ { autoIncrement: false },+ { typeObj: { type: 'Integer' }, autoIncrement: false },+ { typeObj: { type: 'Long' } },+ { comment: 'New comment', autoIncrement: undefined }+ ])('allows changes with no conflict on the column (%j)', changes => {+ const newColumn = { ...originalColumn, ...changes }++ expect(hasAutoIncrementEditConflict('jdbc-mysql', [originalColumn], [newColumn])).toBe(false)+ })++ it('treats an absent comment and an empty comment as the same', () => {+ const oldColumn = { ...originalColumn, comment: undefined }+ const newColumn = { ...originalColumn, comment: '', autoIncrement: false }++ expect(hasAutoIncrementEditConflict('jdbc-mysql', [oldColumn], [newColumn])).toBe(false)+ })++ it('allows changing the comment on a different column', () => {+ const otherColumn = { uniqueId: 'name', name: 'name', comment: 'Old comment' }++ const newColumns = [+ { ...originalColumn, autoIncrement: false },+ { ...otherColumn, comment: 'New comment' }+ ]++ expect(hasAutoIncrementEditConflict('jdbc-mysql', [originalColumn, otherColumn], newColumns)).toBe(false)+ })++ it('allows adding a column with both AutoIncrement and a comment', () => {+ const newColumn = { ...originalColumn, uniqueId: 'new_id', name: 'new_id' }++ expect(hasAutoIncrementEditConflict('jdbc-mysql', [], [newColumn])).toBe(false)+ })++ it('does not apply the MySQL and OceanBase safeguard to PostgreSQL', () => {+ const newColumn = { ...originalColumn, name: 'user_id', comment: 'New comment', autoIncrement: false }++ expect(hasAutoIncrementEditConflict('jdbc-postgresql', [originalColumn], [newColumn])).toBe(false)+ })+})diff --git a/web-v2/web/src/lib/utils/index.js b/web-v2/web/src/lib/utils/index.jsindex aa5d787869..7943e732e9 100644--- a/web-v2/web/src/lib/utils/index.js+++ b/web-v2/web/src/lib/utils/index.js@@ -19,7 +19,7 @@import _, { intersectionWith, isEqual, mergeWith, unionWith } from 'lodash-es'import { isArray, isObject } from './is'-import { ColumnSpesicalType } from '@/config'+import { ColumnSpesicalType, ColumnTypeSupportAutoIncrement } from '@/config'import dayjs from 'dayjs'import { original } from '@reduxjs/toolkit'@@ -33,6 +33,37 @@ const getColumnType = type => {}}+export const isAutoIncrementColumnTypeSupported = type => {+ if (typeof type !== 'string') return false++ return ColumnTypeSupportAutoIncrement.includes(type.trim().toLowerCase())+}++export const hasAutoIncrementEditConflict = (provider, originalColumns, newColumns) => {+ if (!['jdbc-mysql', 'jdbc-oceanbase'].includes(provider)) return false++ const originalColumnsMap = _.keyBy(originalColumns || [], 'uniqueId')++ return (newColumns || []).some(newColumn => {+ if (!newColumn?.uniqueId || typeof newColumn.autoIncrement !== 'boolean') return false++ const originalColumn = originalColumnsMap[newColumn.uniqueId]+ if (!originalColumn || Boolean(originalColumn.autoIncrement) === newColumn.autoIncrement) return false++ const originalType = originalColumn.type && getColumnType(originalColumn.type)+ const editedType = newColumn.typeObj?.type+ const wasRequired = !originalColumn.nullable++ return (+ (!newColumn.autoIncrement && originalColumn.name !== newColumn.name) ||+ (originalColumn.comment || '') !== (newColumn.comment || '') ||+ hasColumnDefaultValueChanged(originalColumn.defaultValue, newColumn.defaultValue) ||+ (typeof newColumn.required === 'boolean' && newColumn.required !== wasRequired) ||+ (originalType && editedType && originalType.toLowerCase() !== editedType.toLowerCase())+ )+ })+}+export const isDevEnv = process.env.NODE_ENV === 'development'export const isProdEnv = process.env.NODE_ENV === 'production'@@ -65,6 +96,55 @@ export const loggerGitHubInfo = (stars, forks) => {)}+export const normalizeColumnDefaultValue = expression => {+ if (expression == null) return undefined+ if (typeof expression !== 'object') return expression+ if (!expression.type && expression.value === undefined) return undefined++ switch (expression.type) {+ case 'literal':+ return {+ type: 'literal',+ dataType: expression.dataType || 'string',+ value: expression.value+ }++ case 'field': {+ const fieldName = expression.fieldName++ return {+ type: 'field',+ fieldName: Array.isArray(fieldName) ? fieldName : [fieldName]+ }+ }++ case 'function':+ return {+ type: 'function',+ funcName: expression.funcName,+ funcArgs: (expression.funcArgs ?? []).map(normalizeColumnDefaultValue)+ }++ case 'unparsed':+ return {+ type: 'unparsed',+ unparsedExpression: expression.value !== undefined ? expression.value : expression.unparsedExpression+ }++ default:+ return expression.type+ ? expression+ : {+ type: 'literal',+ dataType: expression.dataType || 'string',+ value: expression.value+ }+ }+}++const hasColumnDefaultValueChanged = (saved, edited) =>+ !isEqual(normalizeColumnDefaultValue(saved), normalizeColumnDefaultValue(edited))+export const genUpdates = (originalData, newData, disableUpdate = false) => {const updates = []@@ -154,6 +234,7 @@ export const genUpdates = (originalData, newData, disableUpdate = false) => {fieldName: [newColumn.name],type: newColumn.type,nullable: newColumn.nullable,+ autoIncrement: Boolean(newColumn.autoIncrement),comment: newColumn.comment,...(newColumn.defaultValue !== undefined && newColumn.defaultValue !== null? { defaultValue: newColumn.defaultValue }@@ -190,7 +271,19 @@ export const genUpdates = (originalData, newData, disableUpdate = false) => {nullable: newColumnsMap[key].nullable})}- if (JSON.stringify(originalColumnsMap[key].defaultValue) !== JSON.stringify(newColumnsMap[key].defaultValue)) {+ const newAutoIncrement = newColumnsMap[key].autoIncrement+ if (+ newAutoIncrement !== undefined &&+ newAutoIncrement !== null &&+ Boolean(originalColumnsMap[key].autoIncrement) !== Boolean(newAutoIncrement)+ ) {+ updates.push({+ '@type': 'updateColumnAutoIncrement',+ fieldName: [newColumnsMap[key].name],+ autoIncrement: Boolean(newColumnsMap[key].autoIncrement)+ })+ }+ if (hasColumnDefaultValueChanged(originalColumnsMap[key].defaultValue, newColumnsMap[key].defaultValue)) {updates.push({'@type': 'updateColumnDefaultValue',fieldName: [newColumnsMap[key].name],