fsk119 commented on code in PR #22063: URL: https://github.com/apache/flink/pull/22063#discussion_r1152662708
########## flink-table/flink-sql-client/src/main/java/org/apache/flink/table/client/cli/parser/SqlClientSyntaxHighlighter.java: ########## @@ -0,0 +1,257 @@ +/* + * 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.flink.table.client.cli.parser; + +import org.apache.flink.table.api.SqlDialect; +import org.apache.flink.table.api.config.TableConfigOptions; +import org.apache.flink.table.client.config.SqlClientOptions; +import org.apache.flink.table.client.gateway.Executor; + +import org.jline.reader.LineReader; +import org.jline.reader.impl.DefaultHighlighter; +import org.jline.utils.AttributedString; +import org.jline.utils.AttributedStringBuilder; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.io.IOException; +import java.io.InputStream; +import java.util.Arrays; +import java.util.Collections; +import java.util.Comparator; +import java.util.List; +import java.util.Locale; +import java.util.Properties; +import java.util.Set; +import java.util.function.BiConsumer; +import java.util.function.Function; +import java.util.stream.Collectors; + +/** Sql Client syntax highlighter. */ +public class SqlClientSyntaxHighlighter extends DefaultHighlighter { + private static final Logger LOG = LoggerFactory.getLogger(SqlClientSyntaxHighlighter.class); + private static Set<String> flinkKeywordSet; + private static Set<Character> flinkKeywordCharacterSet; Review Comment: flinkKeyWordSet -> keywords flinkKeywordCharacterSet -> keywordCharacters It's a little verbose to add `flink`? ########## flink-table/flink-sql-client/src/main/java/org/apache/flink/table/client/cli/parser/SqlClientSyntaxHighlighter.java: ########## @@ -0,0 +1,257 @@ +/* + * 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.flink.table.client.cli.parser; + +import org.apache.flink.table.api.SqlDialect; +import org.apache.flink.table.api.config.TableConfigOptions; +import org.apache.flink.table.client.config.SqlClientOptions; +import org.apache.flink.table.client.gateway.Executor; + +import org.jline.reader.LineReader; +import org.jline.reader.impl.DefaultHighlighter; +import org.jline.utils.AttributedString; +import org.jline.utils.AttributedStringBuilder; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.io.IOException; +import java.io.InputStream; +import java.util.Arrays; +import java.util.Collections; +import java.util.Comparator; +import java.util.List; +import java.util.Locale; +import java.util.Properties; +import java.util.Set; +import java.util.function.BiConsumer; +import java.util.function.Function; +import java.util.stream.Collectors; + +/** Sql Client syntax highlighter. */ +public class SqlClientSyntaxHighlighter extends DefaultHighlighter { + private static final Logger LOG = LoggerFactory.getLogger(SqlClientSyntaxHighlighter.class); + private static Set<String> flinkKeywordSet; + private static Set<Character> flinkKeywordCharacterSet; + + static { + try (InputStream is = + SqlClientSyntaxHighlighter.class.getResourceAsStream("/keywords.properties")) { + Properties props = new Properties(); + props.load(is); + flinkKeywordSet = + Collections.unmodifiableSet( + Arrays.stream(props.get("default").toString().split(";")) + .collect(Collectors.toSet())); + flinkKeywordCharacterSet = + flinkKeywordSet.stream() + .flatMap(t -> t.chars().mapToObj(c -> (char) c)) + .collect(Collectors.toSet()); + } catch (IOException e) { + LOG.error("Exception: ", e); + flinkKeywordSet = Collections.emptySet(); + } + } + + private final Executor executor; + + public SqlClientSyntaxHighlighter(Executor executor) { + this.executor = executor; + } + + @Override + public AttributedString highlight(LineReader reader, String buffer) { + final SyntaxHighlightStyle.BuiltInStyle style = + SyntaxHighlightStyle.BuiltInStyle.fromString( + executor.getSessionConfig() + .get(SqlClientOptions.DISPLAY_DEFAULT_COLOR_SCHEMA)); + + if (style == SyntaxHighlightStyle.BuiltInStyle.DEFAULT) { + return super.highlight(reader, buffer); + } + final String dialectName = + executor.getSessionConfig().get(TableConfigOptions.TABLE_SQL_DIALECT); + final SqlDialect dialect = + SqlDialect.HIVE.name().equalsIgnoreCase(dialectName) + ? SqlDialect.HIVE + : SqlDialect.DEFAULT; + return getHighlightedOutput(buffer, style.getHighlightStyle(), dialect); + } + + static AttributedString getHighlightedOutput( + String buffer, SyntaxHighlightStyle style, SqlDialect dialect) { + final AttributedStringBuilder highlightedOutput = new AttributedStringBuilder(); + State currentParseState = null; + StringBuilder word = new StringBuilder(); + for (int i = 0; i < buffer.length(); i++) { + final char currentChar = buffer.charAt(i); + if (currentParseState == null) { + currentParseState = State.computeStateAt(buffer, i, dialect); + if (currentParseState == null) { + if (!flinkKeywordCharacterSet.contains(Character.toUpperCase(currentChar))) { + handleWord(word, highlightedOutput, currentParseState, style, true); + highlightedOutput.append(currentChar); + } else { + word.append(currentChar); + } + } else { + handleWord(word, highlightedOutput, null, style, true); + currentParseState.getStyleSetter().accept(highlightedOutput, style); + highlightedOutput.append(currentParseState.getStart()); + i += currentParseState.getStart().length() - 1; + } + } else { + word.append(currentChar); + final String stateEnd = currentParseState.getEnd(); + if (buffer.regionMatches(i, stateEnd, 0, stateEnd.length())) { + handleWord(word, highlightedOutput, currentParseState, style, true); + i += stateEnd.length() - 1; + currentParseState = null; + } + } + } + handleWord(word, highlightedOutput, currentParseState, style, false); + return highlightedOutput.toAttributedString(); + } + + private static void handleWord( + StringBuilder word, + AttributedStringBuilder sb, + State currentState, + SyntaxHighlightStyle style, + boolean turnOffHighlight) { Review Comment: I am confused why we can not infer turnOffHightlight from the state. ########## flink-table/flink-sql-client/src/main/java/org/apache/flink/table/client/cli/parser/SqlClientSyntaxHighlighter.java: ########## @@ -0,0 +1,257 @@ +/* + * 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.flink.table.client.cli.parser; + +import org.apache.flink.table.api.SqlDialect; +import org.apache.flink.table.api.config.TableConfigOptions; +import org.apache.flink.table.client.config.SqlClientOptions; +import org.apache.flink.table.client.gateway.Executor; + +import org.jline.reader.LineReader; +import org.jline.reader.impl.DefaultHighlighter; +import org.jline.utils.AttributedString; +import org.jline.utils.AttributedStringBuilder; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.io.IOException; +import java.io.InputStream; +import java.util.Arrays; +import java.util.Collections; +import java.util.Comparator; +import java.util.List; +import java.util.Locale; +import java.util.Properties; +import java.util.Set; +import java.util.function.BiConsumer; +import java.util.function.Function; +import java.util.stream.Collectors; + +/** Sql Client syntax highlighter. */ +public class SqlClientSyntaxHighlighter extends DefaultHighlighter { + private static final Logger LOG = LoggerFactory.getLogger(SqlClientSyntaxHighlighter.class); + private static Set<String> flinkKeywordSet; + private static Set<Character> flinkKeywordCharacterSet; + + static { + try (InputStream is = + SqlClientSyntaxHighlighter.class.getResourceAsStream("/keywords.properties")) { + Properties props = new Properties(); + props.load(is); + flinkKeywordSet = + Collections.unmodifiableSet( + Arrays.stream(props.get("default").toString().split(";")) + .collect(Collectors.toSet())); + flinkKeywordCharacterSet = + flinkKeywordSet.stream() + .flatMap(t -> t.chars().mapToObj(c -> (char) c)) + .collect(Collectors.toSet()); + } catch (IOException e) { + LOG.error("Exception: ", e); + flinkKeywordSet = Collections.emptySet(); + } + } + + private final Executor executor; + + public SqlClientSyntaxHighlighter(Executor executor) { + this.executor = executor; + } + + @Override + public AttributedString highlight(LineReader reader, String buffer) { + final SyntaxHighlightStyle.BuiltInStyle style = + SyntaxHighlightStyle.BuiltInStyle.fromString( + executor.getSessionConfig() + .get(SqlClientOptions.DISPLAY_DEFAULT_COLOR_SCHEMA)); + + if (style == SyntaxHighlightStyle.BuiltInStyle.DEFAULT) { + return super.highlight(reader, buffer); + } + final String dialectName = + executor.getSessionConfig().get(TableConfigOptions.TABLE_SQL_DIALECT); + final SqlDialect dialect = + SqlDialect.HIVE.name().equalsIgnoreCase(dialectName) + ? SqlDialect.HIVE + : SqlDialect.DEFAULT; + return getHighlightedOutput(buffer, style.getHighlightStyle(), dialect); + } + + static AttributedString getHighlightedOutput( + String buffer, SyntaxHighlightStyle style, SqlDialect dialect) { + final AttributedStringBuilder highlightedOutput = new AttributedStringBuilder(); + State currentParseState = null; + StringBuilder word = new StringBuilder(); + for (int i = 0; i < buffer.length(); i++) { + final char currentChar = buffer.charAt(i); + if (currentParseState == null) { + currentParseState = State.computeStateAt(buffer, i, dialect); + if (currentParseState == null) { + if (!flinkKeywordCharacterSet.contains(Character.toUpperCase(currentChar))) { + handleWord(word, highlightedOutput, currentParseState, style, true); + highlightedOutput.append(currentChar); + } else { + word.append(currentChar); + } + } else { + handleWord(word, highlightedOutput, null, style, true); + currentParseState.getStyleSetter().accept(highlightedOutput, style); + highlightedOutput.append(currentParseState.getStart()); + i += currentParseState.getStart().length() - 1; + } + } else { + word.append(currentChar); + final String stateEnd = currentParseState.getEnd(); + if (buffer.regionMatches(i, stateEnd, 0, stateEnd.length())) { + handleWord(word, highlightedOutput, currentParseState, style, true); + i += stateEnd.length() - 1; + currentParseState = null; + } + } + } + handleWord(word, highlightedOutput, currentParseState, style, false); + return highlightedOutput.toAttributedString(); + } + + private static void handleWord( + StringBuilder word, + AttributedStringBuilder sb, + State currentState, Review Comment: add `@Nullable` ########## flink-table/flink-sql-client/src/test/java/org/apache/flink/table/client/cli/parser/SqlClientHighlighterTest.java: ########## @@ -0,0 +1,165 @@ +/* + * 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.flink.table.client.cli.parser; + +import org.apache.flink.table.api.SqlDialect; + +import org.jline.utils.AttributedStringBuilder; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; + +import java.util.stream.Stream; + +import static org.apache.flink.table.client.cli.parser.SyntaxHighlightStyle.BuiltInStyle.DARK; +import static org.apache.flink.table.client.cli.parser.SyntaxHighlightStyle.BuiltInStyle.LIGHT; +import static org.assertj.core.api.Assertions.assertThat; + +/** Test for {@link SqlClientSyntaxHighlighter}. */ +class SqlClientHighlighterTest { + @ParameterizedTest + @MethodSource("specProvider") + void test(SqlClientHighlighterTestSpec spec) { + assertThat( + SqlClientSyntaxHighlighter.getHighlightedOutput( + spec.sql, spec.style, spec.dialect) + .toAnsi()) + .isEqualTo(spec.getExpected()); + } + + static Stream<SqlClientHighlighterTestSpec> specProvider() { + return Stream.of( + new SqlClientHighlighterTestSpec( + "select", + new AttributedStringTestSpecBuilder(DARK.getHighlightStyle()) + .appendKeyword("select")), + new SqlClientHighlighterTestSpec( + "default_style", + new AttributedStringTestSpecBuilder(DARK.getHighlightStyle()) + .append("default_style")), + new SqlClientHighlighterTestSpec( + "'quoted'", + new AttributedStringTestSpecBuilder(LIGHT.getHighlightStyle()) + .appendQuoted("'quoted'")), + new SqlClientHighlighterTestSpec( + "`sqlQuoteIdentifier`", + new AttributedStringTestSpecBuilder(LIGHT.getHighlightStyle()) + .appendSqlIdentifier("`sqlQuoteIdentifier`")), + new SqlClientHighlighterTestSpec( + "/*\nmultiline\n comment\n*/", + new AttributedStringTestSpecBuilder(LIGHT.getHighlightStyle()) + .appendComment("/*\nmultiline\n comment\n*/")), + new SqlClientHighlighterTestSpec( + "/*\nnot finished\nmultiline\n comment\n", + new AttributedStringTestSpecBuilder(LIGHT.getHighlightStyle()) + .appendComment("/*\nnot finished\nmultiline\n comment\n")), + new SqlClientHighlighterTestSpec( + "/*+hint*/", + new AttributedStringTestSpecBuilder(LIGHT.getHighlightStyle()) + .appendHint("/*+hint*/")), + new SqlClientHighlighterTestSpec( + "'`not a sql quote`''/*not a comment*/''--not a comment'", + new AttributedStringTestSpecBuilder(LIGHT.getHighlightStyle()) + .appendQuoted( + "'`not a sql quote`''/*not a comment*/''--not a comment'")), + new SqlClientHighlighterTestSpec( + "`'not a quote'``/*not a comment*/``--not a comment`", + new AttributedStringTestSpecBuilder(LIGHT.getHighlightStyle()) + .appendSqlIdentifier( + "`'not a quote'``/*not a comment*/``--not a comment`")), + new SqlClientHighlighterTestSpec( + "/*'not a quote'`not a sql quote``` /*+ not a hint*/", + new AttributedStringTestSpecBuilder(LIGHT.getHighlightStyle()) + .appendComment( + "/*'not a quote'`not a sql quote``` /*+ not a hint*/")), + new SqlClientHighlighterTestSpec( + "select/*+ hint*/'1'as`one`/*comment*/from--\ndual;", + new AttributedStringTestSpecBuilder(LIGHT.getHighlightStyle()) + .appendKeyword("select") + .appendHint("/*+ hint*/") + .appendQuoted("'1'") + .appendKeyword("as") + .appendSqlIdentifier("`one`") + .appendComment("/*comment*/") + .appendKeyword("from") + .appendComment("--\n") + .append("dual;"))); + } + + static class SqlClientHighlighterTestSpec { Review Comment: add a `toString` method here ########## flink-table/flink-sql-client/src/main/java/org/apache/flink/table/client/cli/parser/SqlClientSyntaxHighlighter.java: ########## @@ -0,0 +1,257 @@ +/* + * 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.flink.table.client.cli.parser; + +import org.apache.flink.table.api.SqlDialect; +import org.apache.flink.table.api.config.TableConfigOptions; +import org.apache.flink.table.client.config.SqlClientOptions; +import org.apache.flink.table.client.gateway.Executor; + +import org.jline.reader.LineReader; +import org.jline.reader.impl.DefaultHighlighter; +import org.jline.utils.AttributedString; +import org.jline.utils.AttributedStringBuilder; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.io.IOException; +import java.io.InputStream; +import java.util.Arrays; +import java.util.Collections; +import java.util.Comparator; +import java.util.List; +import java.util.Locale; +import java.util.Properties; +import java.util.Set; +import java.util.function.BiConsumer; +import java.util.function.Function; +import java.util.stream.Collectors; + +/** Sql Client syntax highlighter. */ +public class SqlClientSyntaxHighlighter extends DefaultHighlighter { + private static final Logger LOG = LoggerFactory.getLogger(SqlClientSyntaxHighlighter.class); + private static Set<String> flinkKeywordSet; + private static Set<Character> flinkKeywordCharacterSet; + + static { + try (InputStream is = + SqlClientSyntaxHighlighter.class.getResourceAsStream("/keywords.properties")) { + Properties props = new Properties(); + props.load(is); + flinkKeywordSet = + Collections.unmodifiableSet( + Arrays.stream(props.get("default").toString().split(";")) + .collect(Collectors.toSet())); + flinkKeywordCharacterSet = + flinkKeywordSet.stream() + .flatMap(t -> t.chars().mapToObj(c -> (char) c)) + .collect(Collectors.toSet()); + } catch (IOException e) { + LOG.error("Exception: ", e); + flinkKeywordSet = Collections.emptySet(); + } + } + + private final Executor executor; + + public SqlClientSyntaxHighlighter(Executor executor) { + this.executor = executor; + } + + @Override + public AttributedString highlight(LineReader reader, String buffer) { + final SyntaxHighlightStyle.BuiltInStyle style = + SyntaxHighlightStyle.BuiltInStyle.fromString( + executor.getSessionConfig() + .get(SqlClientOptions.DISPLAY_DEFAULT_COLOR_SCHEMA)); Review Comment: If user set an illegal value, whether the sql client can still work? ########## flink-table/flink-sql-client/src/main/resources/keywords.properties: ########## @@ -0,0 +1,20 @@ +# 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. +# +# Resources for the Apache Calcite project. +# See wrapper class org.apache.calcite.runtime.CalciteResource. +# +default=ABS;ALL;ALLOCATE;ALLOW;ALTER;AND;ANY;ARE;ARRAY;ARRAY_AGG;ARRAY_CONCAT_AGG;ARRAY_MAX_CARDINALITY;AS;ASENSITIVE;ASYMMETRIC;AT;ATOMIC;AUTHORIZATION;AVG;BEGIN;BEGIN_FRAME;BEGIN_PARTITION;BETWEEN;BIGINT;BINARY;BIT;BLOB;BOOLEAN;BOTH;BY;BYTES;CALL;CALLED;CARDINALITY;CASCADED;CASE;CAST;CATALOGS;CEIL;CEILING;CHAR;CHARACTER;CHARACTER_LENGTH;CHAR_LENGTH;CHECK;CLASSIFIER;CLOB;CLOSE;COALESCE;COLLATE;COLLECT;COLUMN;COMMENT;COMMIT;CONDITION;CONNECT;CONSTRAINT;CONTAINS;CONVERT;CORR;CORRESPONDING;COUNT;COVAR_POP;COVAR_SAMP;CREATE;CROSS;CUBE;CUME_DIST;CURRENT;CURRENT_CATALOG;CURRENT_DATE;CURRENT_DEFAULT_TRANSFORM_GROUP;CURRENT_PATH;CURRENT_ROLE;CURRENT_ROW;CURRENT_SCHEMA;CURRENT_TIME;CURRENT_TIMESTAMP;CURRENT_TRANSFORM_GROUP_FOR_TYPE;CURRENT_USER;CURSOR;CYCLE;DATABASES;DATE;DAY;DEALLOCATE;DEC;DECIMAL;DECLARE;DEFAULT;DEFINE;DELETE;DENSE_RANK;DEREF;DESCRIBE;DETERMINISTIC;DISALLOW;DISCONNECT;DISTINCT;DOT;DOUBLE;DROP;DYNAMIC;EACH;ELEMENT;ELSE;EMPTY;END;END-EXEC;END_FRAME;END_PARTITION;EQUALS;ESCA PE;EVERY;EXCEPT;EXEC;EXECUTE;EXISTS;EXP;EXPLAIN;EXTEND;EXTENDED;EXTERNAL;EXTRACT;FALSE;FETCH;FILTER;FIRST_VALUE;FLOAT;FLOOR;FOR;FOREIGN;FRAME_ROW;FREE;FROM;FULL;FUNCTION;FUNCTIONS;FUSION;GET;GLOBAL;GRANT;GROUP;GROUPING;GROUPS;GROUP_CONCAT;HAVING;HOLD;HOUR;IDENTITY;ILIKE;IMPORT;IN;INCLUDE;INDICATOR;INITIAL;INNER;INOUT;INSENSITIVE;INSERT;INT;INTEGER;INTERSECT;INTERSECTION;INTERVAL;INTO;IS;JOIN;JSON_ARRAY;JSON_ARRAYAGG;JSON_EXISTS;JSON_OBJECT;JSON_OBJECTAGG;JSON_QUERY;JSON_VALUE;LAG;LANGUAGE;LARGE;LAST_VALUE;LATERAL;LEAD;LEADING;LEFT;LIKE;LIKE_REGEX;LIMIT;LN;LOCAL;LOCALTIME;LOCALTIMESTAMP;LOWER;MATCH;MATCHES;MATCH_NUMBER;MATCH_RECOGNIZE;MAX;MEASURES;MEMBER;MERGE;METHOD;MIN;MINUS;MINUTE;MOD;MODIFIES;MODIFY;MODULE;MODULES;MONTH;MULTISET;NATIONAL;NATURAL;NCHAR;NCLOB;NEW;NEXT;NO;NONE;NORMALIZE;NOT;NTH_VALUE;NTILE;NULL;NULLIF;NUMERIC;OCCURRENCES_REGEX;OCTET_LENGTH;OF;OFFSET;OLD;OMIT;ON;ONE;ONLY;OPEN;OR;ORDER;OUT;OUTER;OVER;OVERLAPS;OVERLAY;PARAMETER;PARTITION;PATTERN;PER;PERCENT;PERCENTILE_ CONT;PERCENTILE_DISC;PERCENT_RANK;PERIOD;PERMUTE;PIVOT;PORTION;POSITION;POSITION_REGEX;POWER;PRECEDES;PRECISION;PREPARE;PREV;PRIMARY;PROCEDURE;RANGE;RANK;RAW;READS;REAL;RECURSIVE;REF;REFERENCES;REFERENCING;REGR_AVGX;REGR_AVGY;REGR_COUNT;REGR_INTERCEPT;REGR_R2;REGR_SLOPE;REGR_SXX;REGR_SXY;REGR_SYY;RELEASE;RENAME;RESET;RESULT;RETURN;RETURNS;REVOKE;RIGHT;RLIKE;ROLLBACK;ROLLUP;ROW;ROWS;ROW_NUMBER;RUNNING;SAVEPOINT;SCALA;SCOPE;SCROLL;SEARCH;SECOND;SEEK;SELECT;SENSITIVE;SEPARATOR;SESSION_USER;SET;SHOW;SIMILAR;SKIP;SMALLINT;SOME;SPECIFIC;SPECIFICTYPE;SQL;SQLEXCEPTION;SQLSTATE;SQLWARNING;SQRT;START;STATEMENT;STATIC;STDDEV_POP;STDDEV_SAMP;STREAM;STRING;STRING_AGG;SUBMULTISET;SUBSET;SUBSTRING;SUBSTRING_REGEX;SUCCEEDS;SUM;SYMMETRIC;SYSTEM;SYSTEM_TIME;SYSTEM_USER;TABLE;TABLES;TABLESAMPLE;THEN;TIME;TIMESTAMP;TIMESTAMP_LTZ;TIMEZONE_HOUR;TIMEZONE_MINUTE;TINYINT;TO;TRAILING;TRANSLATE;TRANSLATE_REGEX;TRANSLATION;TREAT;TRIGGER;TRIM;TRIM_ARRAY;TRUE;TRUNCATE;UESCAPE;UNION;UNIQUE;UNKNOWN;UNNEST;UNPIVOT; UPDATE;UPPER;UPSERT;USE;USER;USING;VALUE;VALUES;VALUE_OF;VARBINARY;VARCHAR;VARYING;VAR_POP;VAR_SAMP;VERSIONING;VIEWS;WATERMARK;WATERMARKS;WHEN;WHENEVER;WHERE;WIDTH_BUCKET;WINDOW;WITH;WITHIN;WITHOUT;YEAR Review Comment: If so, can we just use ``` FlinkSqlParserImpl.FACTORY .getParser(new StringReader("")) .getMetadata() .getJdbcKeywords()) ``` to get the keywords directly here? But I find we can not exclude the calcite-core in the pom. Could you share some thoughts about why we need to exclude this? ########## flink-table/flink-sql-client/src/main/java/org/apache/flink/table/client/cli/parser/SqlClientSyntaxHighlighter.java: ########## @@ -0,0 +1,257 @@ +/* + * 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.flink.table.client.cli.parser; + +import org.apache.flink.table.api.SqlDialect; +import org.apache.flink.table.api.config.TableConfigOptions; +import org.apache.flink.table.client.config.SqlClientOptions; +import org.apache.flink.table.client.gateway.Executor; + +import org.jline.reader.LineReader; +import org.jline.reader.impl.DefaultHighlighter; +import org.jline.utils.AttributedString; +import org.jline.utils.AttributedStringBuilder; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.io.IOException; +import java.io.InputStream; +import java.util.Arrays; +import java.util.Collections; +import java.util.Comparator; +import java.util.List; +import java.util.Locale; +import java.util.Properties; +import java.util.Set; +import java.util.function.BiConsumer; +import java.util.function.Function; +import java.util.stream.Collectors; + +/** Sql Client syntax highlighter. */ +public class SqlClientSyntaxHighlighter extends DefaultHighlighter { + private static final Logger LOG = LoggerFactory.getLogger(SqlClientSyntaxHighlighter.class); + private static Set<String> flinkKeywordSet; + private static Set<Character> flinkKeywordCharacterSet; + + static { + try (InputStream is = + SqlClientSyntaxHighlighter.class.getResourceAsStream("/keywords.properties")) { + Properties props = new Properties(); + props.load(is); + flinkKeywordSet = + Collections.unmodifiableSet( + Arrays.stream(props.get("default").toString().split(";")) + .collect(Collectors.toSet())); + flinkKeywordCharacterSet = + flinkKeywordSet.stream() + .flatMap(t -> t.chars().mapToObj(c -> (char) c)) + .collect(Collectors.toSet()); + } catch (IOException e) { + LOG.error("Exception: ", e); + flinkKeywordSet = Collections.emptySet(); + } + } + + private final Executor executor; + + public SqlClientSyntaxHighlighter(Executor executor) { + this.executor = executor; + } + + @Override + public AttributedString highlight(LineReader reader, String buffer) { + final SyntaxHighlightStyle.BuiltInStyle style = + SyntaxHighlightStyle.BuiltInStyle.fromString( + executor.getSessionConfig() + .get(SqlClientOptions.DISPLAY_DEFAULT_COLOR_SCHEMA)); + + if (style == SyntaxHighlightStyle.BuiltInStyle.DEFAULT) { + return super.highlight(reader, buffer); + } + final String dialectName = + executor.getSessionConfig().get(TableConfigOptions.TABLE_SQL_DIALECT); + final SqlDialect dialect = + SqlDialect.HIVE.name().equalsIgnoreCase(dialectName) + ? SqlDialect.HIVE + : SqlDialect.DEFAULT; + return getHighlightedOutput(buffer, style.getHighlightStyle(), dialect); + } + + static AttributedString getHighlightedOutput( + String buffer, SyntaxHighlightStyle style, SqlDialect dialect) { + final AttributedStringBuilder highlightedOutput = new AttributedStringBuilder(); + State currentParseState = null; + StringBuilder word = new StringBuilder(); + for (int i = 0; i < buffer.length(); i++) { + final char currentChar = buffer.charAt(i); + if (currentParseState == null) { + currentParseState = State.computeStateAt(buffer, i, dialect); + if (currentParseState == null) { + if (!flinkKeywordCharacterSet.contains(Character.toUpperCase(currentChar))) { + handleWord(word, highlightedOutput, currentParseState, style, true); + highlightedOutput.append(currentChar); + } else { + word.append(currentChar); + } + } else { + handleWord(word, highlightedOutput, null, style, true); + currentParseState.getStyleSetter().accept(highlightedOutput, style); + highlightedOutput.append(currentParseState.getStart()); + i += currentParseState.getStart().length() - 1; + } + } else { + word.append(currentChar); + final String stateEnd = currentParseState.getEnd(); + if (buffer.regionMatches(i, stateEnd, 0, stateEnd.length())) { + handleWord(word, highlightedOutput, currentParseState, style, true); + i += stateEnd.length() - 1; + currentParseState = null; + } + } + } + handleWord(word, highlightedOutput, currentParseState, style, false); + return highlightedOutput.toAttributedString(); + } + + private static void handleWord( + StringBuilder word, + AttributedStringBuilder sb, + State currentState, + SyntaxHighlightStyle style, + boolean turnOffHighlight) { + final String wordStr = word.toString(); + if (currentState == null) { + if (flinkKeywordSet.contains(wordStr.toUpperCase(Locale.ROOT))) { + sb.style(style.getKeywordStyle()); + } else { + sb.style(style.getDefaultStyle()); + } + sb.append(wordStr); + } else if (turnOffHighlight) { + sb.append(wordStr); + final String stateEnd = currentState.getEnd(); + if (stateEnd.length() > 1) { + sb.append(stateEnd.substring(1)); + } + } else { + sb.append(wordStr); + } + word.setLength(0); + sb.style(style.getDefaultStyle()); + } + + /** + * State of parser while preparing highlighted output. This class represents a state machine. + * + * <pre> + * MultiLine Comment Single Line Comment + * | | + * (/*,*/) | | (--, \n) + * *------------Default-----------------* + * | | + * | | + * *------------* *------------------* + * (/*+,*/) | | | | (', ') + * | | | | + * Hint | | String + * | | + * | | + * *------------* *------------------* + * (", ") | | (`, `) + * | | + * Hive Identifier Flink Default Identifier + * </pre> + */ + private enum State { Review Comment: It's better we can add a State named `Default` to align with the java doc. ########## flink-table/flink-sql-client/src/main/java/org/apache/flink/table/client/cli/parser/SqlClientSyntaxHighlighter.java: ########## @@ -0,0 +1,257 @@ +/* + * 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.flink.table.client.cli.parser; + +import org.apache.flink.table.api.SqlDialect; +import org.apache.flink.table.api.config.TableConfigOptions; +import org.apache.flink.table.client.config.SqlClientOptions; +import org.apache.flink.table.client.gateway.Executor; + +import org.jline.reader.LineReader; +import org.jline.reader.impl.DefaultHighlighter; +import org.jline.utils.AttributedString; +import org.jline.utils.AttributedStringBuilder; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.io.IOException; +import java.io.InputStream; +import java.util.Arrays; +import java.util.Collections; +import java.util.Comparator; +import java.util.List; +import java.util.Locale; +import java.util.Properties; +import java.util.Set; +import java.util.function.BiConsumer; +import java.util.function.Function; +import java.util.stream.Collectors; + +/** Sql Client syntax highlighter. */ +public class SqlClientSyntaxHighlighter extends DefaultHighlighter { + private static final Logger LOG = LoggerFactory.getLogger(SqlClientSyntaxHighlighter.class); + private static Set<String> flinkKeywordSet; + private static Set<Character> flinkKeywordCharacterSet; + + static { + try (InputStream is = + SqlClientSyntaxHighlighter.class.getResourceAsStream("/keywords.properties")) { + Properties props = new Properties(); + props.load(is); + flinkKeywordSet = + Collections.unmodifiableSet( + Arrays.stream(props.get("default").toString().split(";")) + .collect(Collectors.toSet())); + flinkKeywordCharacterSet = + flinkKeywordSet.stream() + .flatMap(t -> t.chars().mapToObj(c -> (char) c)) + .collect(Collectors.toSet()); + } catch (IOException e) { + LOG.error("Exception: ", e); + flinkKeywordSet = Collections.emptySet(); + } + } + + private final Executor executor; + + public SqlClientSyntaxHighlighter(Executor executor) { + this.executor = executor; + } + + @Override + public AttributedString highlight(LineReader reader, String buffer) { + final SyntaxHighlightStyle.BuiltInStyle style = + SyntaxHighlightStyle.BuiltInStyle.fromString( + executor.getSessionConfig() + .get(SqlClientOptions.DISPLAY_DEFAULT_COLOR_SCHEMA)); + + if (style == SyntaxHighlightStyle.BuiltInStyle.DEFAULT) { + return super.highlight(reader, buffer); + } + final String dialectName = + executor.getSessionConfig().get(TableConfigOptions.TABLE_SQL_DIALECT); + final SqlDialect dialect = + SqlDialect.HIVE.name().equalsIgnoreCase(dialectName) + ? SqlDialect.HIVE + : SqlDialect.DEFAULT; + return getHighlightedOutput(buffer, style.getHighlightStyle(), dialect); + } + + static AttributedString getHighlightedOutput( + String buffer, SyntaxHighlightStyle style, SqlDialect dialect) { + final AttributedStringBuilder highlightedOutput = new AttributedStringBuilder(); + State currentParseState = null; + StringBuilder word = new StringBuilder(); + for (int i = 0; i < buffer.length(); i++) { + final char currentChar = buffer.charAt(i); + if (currentParseState == null) { + currentParseState = State.computeStateAt(buffer, i, dialect); + if (currentParseState == null) { + if (!flinkKeywordCharacterSet.contains(Character.toUpperCase(currentChar))) { + handleWord(word, highlightedOutput, currentParseState, style, true); + highlightedOutput.append(currentChar); + } else { + word.append(currentChar); + } + } else { + handleWord(word, highlightedOutput, null, style, true); + currentParseState.getStyleSetter().accept(highlightedOutput, style); + highlightedOutput.append(currentParseState.getStart()); + i += currentParseState.getStart().length() - 1; + } + } else { + word.append(currentChar); + final String stateEnd = currentParseState.getEnd(); + if (buffer.regionMatches(i, stateEnd, 0, stateEnd.length())) { + handleWord(word, highlightedOutput, currentParseState, style, true); + i += stateEnd.length() - 1; + currentParseState = null; + } + } + } + handleWord(word, highlightedOutput, currentParseState, style, false); + return highlightedOutput.toAttributedString(); + } + + private static void handleWord( + StringBuilder word, + AttributedStringBuilder sb, + State currentState, + SyntaxHighlightStyle style, + boolean turnOffHighlight) { + final String wordStr = word.toString(); + if (currentState == null) { + if (flinkKeywordSet.contains(wordStr.toUpperCase(Locale.ROOT))) { + sb.style(style.getKeywordStyle()); + } else { + sb.style(style.getDefaultStyle()); + } + sb.append(wordStr); + } else if (turnOffHighlight) { + sb.append(wordStr); + final String stateEnd = currentState.getEnd(); + if (stateEnd.length() > 1) { + sb.append(stateEnd.substring(1)); + } + } else { + sb.append(wordStr); + } + word.setLength(0); + sb.style(style.getDefaultStyle()); + } + + /** + * State of parser while preparing highlighted output. This class represents a state machine. + * + * <pre> + * MultiLine Comment Single Line Comment + * | | + * (/*,*/) | | (--, \n) + * *------------Default-----------------* + * | | + * | | + * *------------* *------------------* + * (/*+,*/) | | | | (', ') + * | | | | + * Hint | | String + * | | + * | | + * *------------* *------------------* + * (", ") | | (`, `) + * | | + * Hive Identifier Flink Default Identifier + * </pre> + */ Review Comment: ``` /** * State of parser while preparing highlighted output. This class represents a state machine. * * <pre> * MultiLine Comment Single Line Comment * | | * (/*,*/) | | (--, \n) * *------------Default-----------* * | | * | | * *------------* *------------* * (/*+,*/) | | | | (', ') * | | | | * Hint | | String * | | * | | * *------------* *------------* * (", ") | | (`, `) * | | * Hive Identifier Flink Default Identifier * </pre> */ ``` ########## flink-table/flink-sql-client/src/main/java/org/apache/flink/table/client/cli/parser/SqlClientSyntaxHighlighter.java: ########## @@ -0,0 +1,246 @@ +/* + * 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.flink.table.client.cli.parser; + +import org.apache.flink.table.api.SqlDialect; +import org.apache.flink.table.api.config.TableConfigOptions; +import org.apache.flink.table.client.gateway.Executor; + +import org.jline.reader.LineReader; +import org.jline.reader.impl.DefaultHighlighter; +import org.jline.utils.AttributedString; +import org.jline.utils.AttributedStringBuilder; + +import java.io.IOException; +import java.io.InputStream; +import java.util.Arrays; +import java.util.Collections; +import java.util.Comparator; +import java.util.List; +import java.util.Locale; +import java.util.Properties; +import java.util.Set; +import java.util.function.BiConsumer; +import java.util.function.Function; +import java.util.stream.Collectors; + +import static org.apache.flink.table.client.cli.CliClient.COLOR_SCHEMA_VAR; + +/** Sql Client syntax highlighter. */ +public class SqlClientSyntaxHighlighter extends DefaultHighlighter { + private static final Set<String> FLINK_KEYWORD_SET; + private static final Set<String> HIVE_KEYWORD_SET; + + static { + try (InputStream is = + SqlClientSyntaxHighlighter.class.getResourceAsStream("/keywords.properties")) { + Properties props = new Properties(); + props.load(is); + FLINK_KEYWORD_SET = + Collections.unmodifiableSet( + Arrays.stream(props.get("default").toString().split(";")) + .collect(Collectors.toSet())); + HIVE_KEYWORD_SET = + Collections.unmodifiableSet( + Arrays.stream(props.get("hive").toString().split(";")) + .collect(Collectors.toSet())); + } catch (IOException e) { + throw new RuntimeException(e); + } + } + + private final Executor executor; + + public SqlClientSyntaxHighlighter(Executor executor) { + this.executor = executor; + } + + @Override + public AttributedString highlight(LineReader reader, String buffer) { + + final Object colorSchemeOrdinal = reader.getVariable(COLOR_SCHEMA_VAR); + SyntaxHighlightStyle.BuiltInStyle style = + SyntaxHighlightStyle.BuiltInStyle.fromOrdinal( + colorSchemeOrdinal == null ? 0 : (Integer) colorSchemeOrdinal); + if (style == SyntaxHighlightStyle.BuiltInStyle.DEFAULT) { + return super.highlight(reader, buffer); + } + final SqlDialect dialect = + executor.getSessionConfig() + .get(TableConfigOptions.TABLE_SQL_DIALECT) + .equalsIgnoreCase(SqlDialect.HIVE.toString()) + ? SqlDialect.HIVE + : SqlDialect.DEFAULT; + return getHighlightedOutput(buffer, style.getHighlightStyle(), dialect); + } + + static AttributedString getHighlightedOutput( Review Comment:  I draw a pic to describe my code[1] 0.0 WDYT? [1] https://github.com/apache/flink/compare/master...fsk119:flink:highlight?expand=1 -- 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]
