valepakh commented on code in PR #7420:
URL: https://github.com/apache/ignite-3/pull/7420#discussion_r2704253164


##########
modules/cli/src/main/java/org/apache/ignite/internal/cli/decorators/TableDecorator.java:
##########
@@ -22,29 +22,41 @@
 import org.apache.ignite.internal.cli.core.decorator.TerminalOutput;
 import org.apache.ignite.internal.cli.sql.table.Table;
 import org.apache.ignite.internal.cli.util.PlainTableRenderer;
+import org.apache.ignite.internal.cli.util.TableTruncator;
 
 /**
  * Implementation of {@link Decorator} for {@link Table}.
+ *
+ * <p>Uses raw {@code Table} type to match the CLI decorator registry 
infrastructure.
+ * The cast to {@code Table<String>} is safe because all Table instances in 
the CLI are String-typed.
  */
 public class TableDecorator implements Decorator<Table, TerminalOutput> {
     private final boolean plain;
+    private final TableTruncator truncator;
 
     public TableDecorator(boolean plain) {
-        this.plain = plain;
+        this(plain, TruncationConfig.disabled());
     }
 
     /**
-     * Transform {@link Table} to {@link TerminalOutput}.
+     * Creates a new TableDecorator with truncation support.
      *
-     * @param table incoming {@link Table}.
-     * @return User-friendly interpretation of {@link Table} in {@link 
TerminalOutput}.
+     * @param plain whether to use plain formatting
+     * @param truncationConfig truncation configuration
      */
+    public TableDecorator(boolean plain, TruncationConfig truncationConfig) {
+        this.plain = plain;
+        this.truncator = new TableTruncator(truncationConfig);
+    }
+
     @Override
+    @SuppressWarnings("unchecked") // Safe cast: all CLI Table instances are 
Table<String>

Review Comment:
   Redundant suppression



##########
modules/cli/src/main/java/org/apache/ignite/internal/cli/util/TableTruncator.java:
##########
@@ -0,0 +1,238 @@
+/*
+ * 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.
+ */
+
+package org.apache.ignite.internal.cli.util;
+
+import static 
org.apache.ignite.internal.cli.decorators.TruncationConfig.ELLIPSIS;
+
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.List;
+import org.apache.ignite.internal.cli.decorators.TruncationConfig;
+import org.apache.ignite.internal.cli.sql.table.Table;
+
+/**
+ * Truncates table columns to fit terminal width.
+ */
+public class TableTruncator {
+    /** Minimum column width to display at least ellipsis. */
+    private static final int MIN_COLUMN_WIDTH = ELLIPSIS.length();
+
+    /** Characters used for table borders in FlipTables (| and spaces). */
+    private static final int BORDER_OVERHEAD_PER_COLUMN = 3;
+
+    /** Left and right border overhead. */
+    private static final int TABLE_BORDER_OVERHEAD = 2;
+
+    private final TruncationConfig config;
+
+    /**
+     * Creates a new TableTruncator with the given configuration.
+     *
+     * @param config truncation configuration
+     */
+    public TableTruncator(TruncationConfig config) {
+        this.config = config;
+    }
+
+    /**
+     * Truncates table columns based on the truncation configuration.
+     *
+     * @param table the table to truncate
+     * @return a new table with truncated values, or the original table if 
truncation is disabled
+     */
+    public Table<String> truncate(Table<String> table) {
+        if (!config.isTruncateEnabled()) {
+            return table;
+        }
+
+        String[] header = table.header();
+        Object[][] content = table.content();
+
+        if (header.length == 0) {
+            return table;
+        }
+
+        int[] columnWidths = calculateColumnWidths(header, content);
+        String[] truncatedHeader = truncateRow(header, columnWidths);
+        List<String> truncatedContent = truncateContent(content, columnWidths);
+
+        return new Table<>(Arrays.asList(truncatedHeader), truncatedContent);
+    }
+
+    /**
+     * Calculates optimal column widths based on content and terminal 
constraints.
+     *
+     * @param header table header
+     * @param content table content
+     * @return array of column widths
+     */
+    int[] calculateColumnWidths(String[] header, Object[][] content) {
+        int columnCount = header.length;
+        int[] maxContentWidths = new int[columnCount];
+
+        // Calculate maximum content width for each column
+        for (int col = 0; col < columnCount; col++) {
+            maxContentWidths[col] = Math.max(maxContentWidths[col], 
stringLength(header[col]));
+            for (Object[] row : content) {
+                if (col < row.length) {
+                    maxContentWidths[col] = Math.max(maxContentWidths[col], 
stringLength(row[col]));
+                }
+            }
+        }
+
+        int[] columnWidths = new int[columnCount];
+        int maxColumnWidth = config.getMaxColumnWidth();
+        int terminalWidth = config.getTerminalWidth();
+
+        // Apply max column width constraint
+        for (int col = 0; col < columnCount; col++) {
+            columnWidths[col] = Math.min(maxContentWidths[col], 
maxColumnWidth);
+            columnWidths[col] = Math.max(columnWidths[col], MIN_COLUMN_WIDTH);
+        }
+
+        // Apply terminal width constraint if set
+        if (terminalWidth > 0) {
+            distributeWidthsForTerminal(columnWidths, terminalWidth);
+        }
+
+        return columnWidths;
+    }
+
+    /**
+     * Distributes column widths to fit within terminal width.
+     *
+     * @param columnWidths column widths to adjust (modified in place)
+     * @param terminalWidth terminal width constraint
+     */
+    private void distributeWidthsForTerminal(int[] columnWidths, int 
terminalWidth) {

Review Comment:
   This and following methods could be made static and consequently in the 
`TableTruncatorTest` there's no need to instantiate the truncator.



##########
modules/cli/src/test/java/org/apache/ignite/internal/cli/util/TableTruncatorTest.java:
##########
@@ -0,0 +1,228 @@
+/*
+ * 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.
+ */
+
+package org.apache.ignite.internal.cli.util;
+
+import static org.hamcrest.MatcherAssert.assertThat;
+import static org.hamcrest.Matchers.equalTo;
+import static org.hamcrest.Matchers.is;
+import static org.hamcrest.Matchers.sameInstance;
+
+import java.util.Arrays;
+import java.util.List;
+import org.apache.ignite.internal.cli.decorators.TruncationConfig;
+import org.apache.ignite.internal.cli.sql.table.Table;
+import org.junit.jupiter.api.Test;
+
+/**
+ * Tests for {@link TableTruncator}.
+ */
+class TableTruncatorTest {
+
+    @Test
+    void truncateDisabledReturnsOriginalTable() {
+        Table<String> table = createTable(
+                List.of("id", "name"),
+                List.of("1", "Alice", "2", "Bob")
+        );
+        TruncationConfig config = TruncationConfig.disabled();
+
+        Table<String> result = new TableTruncator(config).truncate(table);
+
+        assertThat(result, sameInstance(table));
+    }
+
+    @Test
+    void truncateCellWithinLimit() {
+        TableTruncator truncator = new TableTruncator(enabledConfig(50));
+
+        String result = truncator.truncateCell("short", 10);
+
+        assertThat(result, equalTo("short"));
+    }
+
+    @Test
+    void truncateCellExceedsLimit() {
+        TableTruncator truncator = new TableTruncator(enabledConfig(50));
+
+        String result = truncator.truncateCell("very long text that exceeds 
the limit", 10);
+
+        assertThat(result, equalTo("very lo..."));
+    }
+
+    @Test
+    void truncateCellExactlyAtLimit() {
+        TableTruncator truncator = new TableTruncator(enabledConfig(50));
+
+        String result = truncator.truncateCell("1234567890", 10);
+
+        assertThat(result, equalTo("1234567890"));
+    }
+
+    @Test
+    void truncateCellNullValue() {
+        TableTruncator truncator = new TableTruncator(enabledConfig(50));
+
+        String result = truncator.truncateCell(null, 10);
+
+        assertThat(result, equalTo("null"));
+    }
+
+    @Test
+    void truncateCellMinimumWidth() {
+        TableTruncator truncator = new TableTruncator(enabledConfig(50));
+
+        String result = truncator.truncateCell("hello", 3);
+
+        assertThat(result, equalTo("..."));
+    }
+
+    @Test
+    void truncateCellWidthLessThanEllipsis() {
+        TableTruncator truncator = new TableTruncator(enabledConfig(50));
+
+        String result = truncator.truncateCell("hello", 2);
+
+        assertThat(result, equalTo(".."));
+    }
+
+    @Test
+    void truncateTableAppliesMaxColumnWidth() {
+        Table<String> table = createTable(
+                List.of("id", "description"),
+                List.of("1", "This is a very long description that should be 
truncated")
+        );
+        TruncationConfig config = new TruncationConfig(true, 20, 0);
+
+        Table<String> result = new TableTruncator(config).truncate(table);
+
+        assertThat(result.header()[1], equalTo("description"));
+        assertThat(result.content()[0][1], equalTo("This is a very lo..."));
+    }
+
+    @Test
+    void truncateTablePreservesShortColumns() {
+        Table<String> table = createTable(
+                List.of("id", "name", "description"),
+                List.of("1", "Alice", "Short desc")
+        );
+        TruncationConfig config = new TruncationConfig(true, 20, 0);
+
+        Table<String> result = new TableTruncator(config).truncate(table);
+
+        assertThat(result.content()[0][0], equalTo("1"));
+        assertThat(result.content()[0][1], equalTo("Alice"));
+        assertThat(result.content()[0][2], equalTo("Short desc"));
+    }
+
+    @Test
+    void truncateEmptyTableReturnsOriginal() {
+        Table<String> table = createTable(List.of("id"), List.of());
+        TruncationConfig config = new TruncationConfig(true, 20, 80);
+
+        Table<String> result = new TableTruncator(config).truncate(table);
+
+        assertThat(result.header().length, is(1));
+        assertThat(result.content().length, is(0));
+    }
+
+    @Test
+    void calculateColumnWidthsRespectsMaxColumnWidth() {
+        String[] header = {"id", "description"};
+        Object[][] content = {{"1", "This is a long description"}};
+        TruncationConfig config = new TruncationConfig(true, 15, 0);
+
+        int[] widths = new 
TableTruncator(config).calculateColumnWidths(header, content);
+
+        assertThat(widths[0], is(3)); // "..." minimum or actual length
+        assertThat(widths[1], is(15)); // capped at max column width
+    }
+
+    @Test
+    void calculateColumnWidthsDistributesForTerminal() {
+        String[] header = {"col1", "col2", "col3"};
+        Object[][] content = {
+                {"very long content 1", "very long content 2", "very long 
content 3"}
+        };
+        // Terminal width = 50, with overhead for borders
+        TruncationConfig config = new TruncationConfig(true, 100, 50);
+
+        int[] widths = new 
TableTruncator(config).calculateColumnWidths(header, content);
+
+        // Total width should fit within terminal width
+        int totalWidth = Arrays.stream(widths).sum();
+        // Account for borders: 2 (outer) + 3 * 3 (column separators) = 11
+        assertThat(totalWidth <= 50 - 11, is(true));

Review Comment:
   Can we also test the result of the truncation, not only the total width?



##########
modules/cli/src/main/java/org/apache/ignite/internal/cli/util/TableTruncator.java:
##########
@@ -0,0 +1,238 @@
+/*
+ * 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.
+ */
+
+package org.apache.ignite.internal.cli.util;
+
+import static 
org.apache.ignite.internal.cli.decorators.TruncationConfig.ELLIPSIS;
+
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.List;
+import org.apache.ignite.internal.cli.decorators.TruncationConfig;
+import org.apache.ignite.internal.cli.sql.table.Table;
+
+/**
+ * Truncates table columns to fit terminal width.
+ */
+public class TableTruncator {
+    /** Minimum column width to display at least ellipsis. */
+    private static final int MIN_COLUMN_WIDTH = ELLIPSIS.length();
+
+    /** Characters used for table borders in FlipTables (| and spaces). */
+    private static final int BORDER_OVERHEAD_PER_COLUMN = 3;
+
+    /** Left and right border overhead. */
+    private static final int TABLE_BORDER_OVERHEAD = 2;
+
+    private final TruncationConfig config;
+
+    /**
+     * Creates a new TableTruncator with the given configuration.
+     *
+     * @param config truncation configuration
+     */
+    public TableTruncator(TruncationConfig config) {
+        this.config = config;
+    }
+
+    /**
+     * Truncates table columns based on the truncation configuration.
+     *
+     * @param table the table to truncate
+     * @return a new table with truncated values, or the original table if 
truncation is disabled
+     */
+    public Table<String> truncate(Table<String> table) {
+        if (!config.isTruncateEnabled()) {
+            return table;
+        }
+
+        String[] header = table.header();
+        Object[][] content = table.content();
+
+        if (header.length == 0) {
+            return table;
+        }
+
+        int[] columnWidths = calculateColumnWidths(header, content);
+        String[] truncatedHeader = truncateRow(header, columnWidths);
+        List<String> truncatedContent = truncateContent(content, columnWidths);
+
+        return new Table<>(Arrays.asList(truncatedHeader), truncatedContent);
+    }
+
+    /**
+     * Calculates optimal column widths based on content and terminal 
constraints.
+     *
+     * @param header table header
+     * @param content table content
+     * @return array of column widths
+     */
+    int[] calculateColumnWidths(String[] header, Object[][] content) {
+        int columnCount = header.length;
+        int[] maxContentWidths = new int[columnCount];
+
+        // Calculate maximum content width for each column
+        for (int col = 0; col < columnCount; col++) {
+            maxContentWidths[col] = Math.max(maxContentWidths[col], 
stringLength(header[col]));
+            for (Object[] row : content) {
+                if (col < row.length) {

Review Comment:
   Is it possible to have `false` here?



##########
modules/cli/src/main/java/org/apache/ignite/internal/cli/commands/sql/SqlExecReplCommand.java:
##########
@@ -220,14 +235,22 @@ private CallExecutionPipelineProvider provider(SqlManager 
sqlManager) {
     }
 
     private CallExecutionPipeline<?, ?> createSqlExecPipeline(SqlManager 
sqlManager, String line) {
+        TruncationConfig truncationConfig = TruncationConfig.fromConfig(
+                configManagerProvider,
+                () -> terminal != null ? terminal.getWidth() : 0,

Review Comment:
   Injected field is never `null` I believe?
   ```suggestion
                   terminal::getWidth,
   ```



##########
modules/cli/src/main/java/org/apache/ignite/internal/cli/decorators/TableDecorator.java:
##########
@@ -22,29 +22,41 @@
 import org.apache.ignite.internal.cli.core.decorator.TerminalOutput;
 import org.apache.ignite.internal.cli.sql.table.Table;
 import org.apache.ignite.internal.cli.util.PlainTableRenderer;
+import org.apache.ignite.internal.cli.util.TableTruncator;
 
 /**
  * Implementation of {@link Decorator} for {@link Table}.
+ *
+ * <p>Uses raw {@code Table} type to match the CLI decorator registry 
infrastructure.
+ * The cast to {@code Table<String>} is safe because all Table instances in 
the CLI are String-typed.
  */
 public class TableDecorator implements Decorator<Table, TerminalOutput> {
     private final boolean plain;
+    private final TableTruncator truncator;
 
     public TableDecorator(boolean plain) {
-        this.plain = plain;
+        this(plain, TruncationConfig.disabled());
     }
 
     /**
-     * Transform {@link Table} to {@link TerminalOutput}.

Review Comment:
   Looks like javadoc for the `decorate` method was lost



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: [email protected]

For queries about this service, please contact Infrastructure at:
[email protected]

Reply via email to