diff --git a/deparser/jsqlparser/src/main/java/org/eclipse/daanse/sql/deparser/jsqlparser/BasicDialectExpressionDeParser.java b/deparser/jsqlparser/src/main/java/org/eclipse/daanse/sql/deparser/jsqlparser/BasicDialectExpressionDeParser.java index 44c3f081..91ceb4fb 100644 --- a/deparser/jsqlparser/src/main/java/org/eclipse/daanse/sql/deparser/jsqlparser/BasicDialectExpressionDeParser.java +++ b/deparser/jsqlparser/src/main/java/org/eclipse/daanse/sql/deparser/jsqlparser/BasicDialectExpressionDeParser.java @@ -15,19 +15,31 @@ import java.util.ArrayDeque; import java.util.Deque; +import java.util.Iterator; +import java.util.List; +import java.util.Map; import java.util.Set; import org.eclipse.daanse.sql.dialect.api.Dialect; import org.eclipse.daanse.sql.dialect.api.IdentifierQuotingPolicy; +import net.sf.jsqlparser.expression.CollateExpression; import net.sf.jsqlparser.expression.DateValue; import net.sf.jsqlparser.expression.DoubleValue; +import net.sf.jsqlparser.expression.Expression; +import net.sf.jsqlparser.expression.JsonExpression; +import net.sf.jsqlparser.expression.KeepExpression; import net.sf.jsqlparser.expression.LongValue; +import net.sf.jsqlparser.expression.OracleHierarchicalExpression; +import net.sf.jsqlparser.expression.operators.relational.FullTextSearch; +import net.sf.jsqlparser.expression.operators.relational.IsDistinctExpression; +import net.sf.jsqlparser.expression.operators.relational.JsonOperator; import net.sf.jsqlparser.expression.StringValue; import net.sf.jsqlparser.expression.TimeValue; import net.sf.jsqlparser.expression.TimestampValue; import net.sf.jsqlparser.schema.Column; import net.sf.jsqlparser.schema.Table; +import net.sf.jsqlparser.statement.select.OrderByElement; import net.sf.jsqlparser.statement.select.SelectVisitor; import net.sf.jsqlparser.util.deparser.ExpressionDeParser; @@ -77,9 +89,9 @@ public StringBuilder visit(Column tableColumn, S context) { String name = table.getName(); if (name != null && !name.isEmpty()) { if (isDeclaredAlias(name)) { - // Alias declared in an enclosing FROM scope — emit verbatim so it - // matches the unquoted alias declaration (case-folding compatible). - builder.append(name).append('.'); + // Alias declared in an enclosing FROM scope — written as its declaration + // is, so that it matches it (an unquoted alias keeps its case folding). + builder.append(aliasName(name, dialect)).append('.'); } else { String catalog = table.getDatabaseName(); String schema = table.getSchemaName(); @@ -157,4 +169,155 @@ public StringBuilder visit(DoubleValue doubleValue, S context) { dialect.quoteNumericLiteral(builder, valueString); return builder; } + + // Expressions the parser's deparser writes with toString(): written here part by part, + // so that each name is quoted by the dialect and each literal is written by it + + @Override + public StringBuilder visit(IsDistinctExpression isDistinct, S context) { + isDistinct.getLeftExpression().accept(this, context); + builder.append(isDistinct.getStringExpression()); + isDistinct.getRightExpression().accept(this, context); + return builder; + } + + @Override + public StringBuilder visit(CollateExpression collate, S context) { + collate.getLeftExpression().accept(this, context); + builder.append(" COLLATE "); + dialect.quoteIdentifierWith(unquoted(collate.getCollate()), builder, IdentifierQuotingPolicy.ALWAYS); + return builder; + } + + @Override + public StringBuilder visit(KeepExpression keep, S context) { + builder.append("KEEP (").append(keep.getName().toUpperCase(java.util.Locale.ROOT)).append(' ') + .append(keep.isFirst() ? "FIRST" : "LAST").append(" ORDER BY "); + orderBy(keep.getOrderByElements(), context); + builder.append(')'); + return builder; + } + + @Override + public StringBuilder visit(JsonExpression json, S context) { + json.getExpression().accept(this, context); + for (Map.Entry ident : json.getIdentList()) { + builder.append(' ').append(ident.getValue().trim()).append(' '); + ident.getKey().accept(this, context); + } + return builder; + } + + @Override + public StringBuilder visit(JsonOperator json, S context) { + json.getLeftExpression().accept(this, context); + builder.append(' ').append(json.getStringExpression().trim()).append(' '); + json.getRightExpression().accept(this, context); + return builder; + } + + @Override + public StringBuilder visit(FullTextSearch search, S context) { + builder.append("MATCH ("); + Iterator columns = search.getMatchColumns().iterator(); + while (columns.hasNext()) { + columns.next().accept(this, context); + if (columns.hasNext()) { + builder.append(", "); + } + } + builder.append(") AGAINST ("); + search.getAgainstValue().accept(this, context); + if (search.getSearchModifier() != null) { + builder.append(' ').append(search.getSearchModifier()); + } + builder.append(')'); + return builder; + } + + @Override + public StringBuilder visit(OracleHierarchicalExpression hierarchical, S context) { + if (hierarchical.isConnectFirst()) { + connectBy(hierarchical, context); + startWith(hierarchical, context); + } else { + startWith(hierarchical, context); + connectBy(hierarchical, context); + } + return builder; + } + + private void startWith(OracleHierarchicalExpression hierarchical, S context) { + if (hierarchical.getStartExpression() != null) { + builder.append(" START WITH "); + hierarchical.getStartExpression().accept(this, context); + } + } + + private void connectBy(OracleHierarchicalExpression hierarchical, S context) { + builder.append(" CONNECT BY "); + if (hierarchical.isNoCycle()) { + builder.append("NOCYCLE "); + } + hierarchical.getConnectExpression().accept(this, context); + } + + /** An ORDER BY list, each expression written by this deparser. */ + void orderBy(List elements, S context) { + Iterator iterator = elements.iterator(); + while (iterator.hasNext()) { + OrderByElement element = iterator.next(); + if (element.getWithFill() != null) { + throw new IllegalStateException("ORDER BY ... WITH FILL cannot be written"); + } + element.getExpression().accept(this, context); + if (!element.isAsc()) { + builder.append(" DESC"); + } else if (element.isAscDescPresent()) { + builder.append(" ASC"); + } + if (element.getNullOrdering() == OrderByElement.NullOrdering.NULLS_FIRST) { + builder.append(" NULLS FIRST"); + } else if (element.getNullOrdering() == OrderByElement.NullOrdering.NULLS_LAST) { + builder.append(" NULLS LAST"); + } + if (iterator.hasNext()) { + builder.append(", "); + } + } + } + + private static final java.util.regex.Pattern PLAIN_IDENTIFIER = java.util.regex.Pattern + .compile("[A-Za-z_][A-Za-z0-9_$]*"); + + /** + * An alias as it is written: a plain identifier as the query wrote it, anything else + * read without its quotes and quoted by the dialect, so that every database reads it + * as one name. + */ + static String aliasName(String name, Dialect dialect) { + if (name == null || PLAIN_IDENTIFIER.matcher(name).matches()) { + return name; + } + return dialect.quoteIdentifierWith(unquoted(name), IdentifierQuotingPolicy.ALWAYS); + } + + /** A name as written without its quotes: {@code "a""b"} is {@code a"b}. */ + static String unquoted(String name) { + if (name == null || name.length() < 2) { + return name; + } + char first = name.charAt(0); + char last = name.charAt(name.length() - 1); + if (first == '"' && last == '"') { + return name.substring(1, name.length() - 1).replace("\"\"", "\""); + } + if (first == '`' && last == '`') { + return name.substring(1, name.length() - 1).replace("``", "`"); + } + if (first == '[' && last == ']') { + return name.substring(1, name.length() - 1).replace("]]", "]"); + } + return name; + } } diff --git a/deparser/jsqlparser/src/main/java/org/eclipse/daanse/sql/deparser/jsqlparser/BasicDialectSelectDeParser.java b/deparser/jsqlparser/src/main/java/org/eclipse/daanse/sql/deparser/jsqlparser/BasicDialectSelectDeParser.java index 02f5b1d6..bbba72a1 100644 --- a/deparser/jsqlparser/src/main/java/org/eclipse/daanse/sql/deparser/jsqlparser/BasicDialectSelectDeParser.java +++ b/deparser/jsqlparser/src/main/java/org/eclipse/daanse/sql/deparser/jsqlparser/BasicDialectSelectDeParser.java @@ -111,8 +111,8 @@ public StringBuilder visit(Table table, S context) { } else { builder.append(" "); } - // Don't quote the alias - it's user-defined and may be intentionally unquoted - builder.append(alias.getName()); + // an unquoted alias is written as it is, so that it keeps its case folding + builder.append(BasicDialectExpressionDeParser.aliasName(alias.getName(), dialect)); } // Handle pivot/unpivot if present @@ -144,7 +144,7 @@ public StringBuilder visit(SelectItem selectItem, S context) { } else { builder.append(" "); } - builder.append(alias.getName()); + builder.append(BasicDialectExpressionDeParser.aliasName(alias.getName(), dialect)); } return builder; diff --git a/dialect/api/src/main/java/org/eclipse/daanse/sql/dialect/api/generator/LiteralQuoter.java b/dialect/api/src/main/java/org/eclipse/daanse/sql/dialect/api/generator/LiteralQuoter.java index 8fb08b20..baca7c4b 100644 --- a/dialect/api/src/main/java/org/eclipse/daanse/sql/dialect/api/generator/LiteralQuoter.java +++ b/dialect/api/src/main/java/org/eclipse/daanse/sql/dialect/api/generator/LiteralQuoter.java @@ -19,6 +19,18 @@ public interface LiteralQuoter { void quoteStringLiteral(StringBuilder buf, String s); + /** + * Whether the database reads a backslash in a string literal as an escape character + * ({@code 'it\'s'}), as MySQL, MariaDB, ClickHouse and Hive do. The SQL standard, and + * PostgreSQL, H2, Oracle, SQL Server and DuckDB, read it as an ordinary character. + * {@link #quoteStringLiteral(StringBuilder, String)} of such a dialect escapes it. + * + * @return {@code true} when a backslash escapes the character after it + */ + default boolean backslashEscapesInStringLiterals() { + return false; + } + void quoteNumericLiteral(StringBuilder buf, String value); void quoteBooleanLiteral(StringBuilder buf, String value); diff --git a/dialect/db/clickhouse/src/main/java/org/eclipse/daanse/sql/dialect/db/clickhouse/ClickHouseDialect.java b/dialect/db/clickhouse/src/main/java/org/eclipse/daanse/sql/dialect/db/clickhouse/ClickHouseDialect.java index 59c86edf..098ae49b 100644 --- a/dialect/db/clickhouse/src/main/java/org/eclipse/daanse/sql/dialect/db/clickhouse/ClickHouseDialect.java +++ b/dialect/db/clickhouse/src/main/java/org/eclipse/daanse/sql/dialect/db/clickhouse/ClickHouseDialect.java @@ -444,6 +444,11 @@ public String unionDistinctKeyword() { return "union distinct"; } + @Override + public boolean backslashEscapesInStringLiterals() { + return true; + } + @Override public void quoteStringLiteral(StringBuilder buf, String s) { buf.append('\''); diff --git a/dialect/db/hive/src/main/java/org/eclipse/daanse/sql/dialect/db/hive/HiveDialect.java b/dialect/db/hive/src/main/java/org/eclipse/daanse/sql/dialect/db/hive/HiveDialect.java index 4fe6bc4f..f9b096d9 100644 --- a/dialect/db/hive/src/main/java/org/eclipse/daanse/sql/dialect/db/hive/HiveDialect.java +++ b/dialect/db/hive/src/main/java/org/eclipse/daanse/sql/dialect/db/hive/HiveDialect.java @@ -45,6 +45,21 @@ public boolean supportsResultSetConcurrency(int type, int concurrency) { return false; } + /** HiveQL (and Impala) read a string literal with C-style escapes. */ + @Override + public boolean backslashEscapesInStringLiterals() { + return true; + } + + /** + * A string literal as HiveQL and Impala read it: a backslash escapes the character after + * it, so a backslash and a quote of the value are each escaped with one. + */ + @Override + public void quoteStringLiteral(StringBuilder buf, String s) { + buf.append('\'').append(s.replace("\\", "\\\\").replace("'", "\\'")).append('\''); + } + @Override public boolean allowsCompoundCountDistinct() { return true; diff --git a/dialect/db/hive/src/test/java/org/eclipse/daanse/sql/dialect/db/hive/HiveDialectTest.java b/dialect/db/hive/src/test/java/org/eclipse/daanse/sql/dialect/db/hive/HiveDialectTest.java index 9341ecbe..3f977844 100644 --- a/dialect/db/hive/src/test/java/org/eclipse/daanse/sql/dialect/db/hive/HiveDialectTest.java +++ b/dialect/db/hive/src/test/java/org/eclipse/daanse/sql/dialect/db/hive/HiveDialectTest.java @@ -146,4 +146,19 @@ void has_no_users() { assertEquals(java.util.Optional.empty(), dialect.createUser("u", false)); assertEquals(java.util.Optional.empty(), dialect.dropUser("u", true)); } + + /** HiveQL reads a string literal with C-style escapes: a quote or backslash ends no string. */ + @Test + void stringLiteralsEscapeQuoteAndBackslash() { + assertTrue(dialect.backslashEscapesInStringLiterals()); + StringBuilder buf = new StringBuilder(); + dialect.quoteStringLiteral(buf, "it's"); + assertEquals("'it\\'s'", buf.toString()); + buf.setLength(0); + dialect.quoteStringLiteral(buf, "a\\"); + assertEquals("'a\\\\'", buf.toString()); + buf.setLength(0); + dialect.quoteStringLiteral(buf, "a\\' or name = ' union select pw from secret -- "); + assertEquals("'a\\\\\\' or name = \\' union select pw from secret -- '", buf.toString()); + } } diff --git a/dialect/db/impala/src/main/java/org/eclipse/daanse/sql/dialect/db/impala/ImpalaDialect.java b/dialect/db/impala/src/main/java/org/eclipse/daanse/sql/dialect/db/impala/ImpalaDialect.java index 9eeff018..2c045454 100644 --- a/dialect/db/impala/src/main/java/org/eclipse/daanse/sql/dialect/db/impala/ImpalaDialect.java +++ b/dialect/db/impala/src/main/java/org/eclipse/daanse/sql/dialect/db/impala/ImpalaDialect.java @@ -100,27 +100,6 @@ public StringBuilder generateInline(List columnNames, List colum return generateInlineGeneric(columnNames, columnTypes, valueList, null, false); } - @Override - public void quoteStringLiteral(StringBuilder buf, String value) { - String quote = "\'"; - String s0 = value; - - if (s0.contains("\\")) { - // NOTE: no-op replacement, kept for behavioral fidelity with the - // legacy (Mondrian-era) dialect — backslashes are never doubled. - s0 = s0.replace("\\\\", "\\\\"); - } - if (s0.contains(quote)) { - s0 = s0.replace(quote, "\\\\" + quote); - } - - buf.append(quote); - - buf.append(s0); - - buf.append(quote); - } - @Override public boolean allowsRegularExpressionInWhereClause() { return true; diff --git a/dialect/db/impala/src/test/java/org/eclipse/daanse/sql/dialect/db/impala/ImpalaDialectTest.java b/dialect/db/impala/src/test/java/org/eclipse/daanse/sql/dialect/db/impala/ImpalaDialectTest.java index 80bd57c8..ce0e5205 100644 --- a/dialect/db/impala/src/test/java/org/eclipse/daanse/sql/dialect/db/impala/ImpalaDialectTest.java +++ b/dialect/db/impala/src/test/java/org/eclipse/daanse/sql/dialect/db/impala/ImpalaDialectTest.java @@ -57,7 +57,9 @@ void testGenerateRegularExpression_CaseInsensitive() { assertTrue(sql.contains("UPPER")); assertTrue(sql.contains("cast(table.column as string)")); assertTrue(sql.contains("REGEXP")); - assertTrue(sql.contains("'\\A(?:.*A.*)\\z'")); + // Impala reads a backslash in a literal as an escape: the regular expression's own + // backslashes are doubled, so that Impala passes \\A and \\z to the matcher + assertTrue(sql.contains("'\\\\A(?:.*A.*)\\\\z'")); } @Test @@ -66,7 +68,9 @@ void testGenerateRegularExpression_CaseSensitive() { assertFalse(sql.contains("UPPER")); assertTrue(sql.contains("cast(table.column as string)")); assertTrue(sql.contains("REGEXP")); - assertTrue(sql.contains("'\\A(?:.*1.*)\\z'")); + // Impala reads a backslash in a literal as an escape: the regular expression's own + // backslashes are doubled, so that Impala passes \\A and \\z to the matcher + assertTrue(sql.contains("'\\\\A(?:.*1.*)\\\\z'")); } @Test @@ -97,11 +101,19 @@ void testGenerateOrderItem_NullableNullsFirst() { dialect.generateOrderItem("column1", true, false, false).toString()); } + /** Impala reads {@code \\'} as an escaped quote, and {@code \\\\} as one backslash. */ @Test void testQuoteStringLiteral() { StringBuilder buf = new StringBuilder(); dialect.quoteStringLiteral(buf, "it's"); - assertEquals("'it\\\\'s'", buf.toString()); + assertEquals("'it\\'s'", buf.toString()); + buf.setLength(0); + dialect.quoteStringLiteral(buf, "a\\"); + assertEquals("'a\\\\'", buf.toString()); + buf.setLength(0); + dialect.quoteStringLiteral(buf, "a\\' or 1=1 --"); + assertEquals("'a\\\\\\' or 1=1 --'", buf.toString()); + assertTrue(dialect.backslashEscapesInStringLiterals()); } @Test diff --git a/dialect/db/mariadb/src/test/java/org/eclipse/daanse/sql/dialect/db/mariadb/container/MariaDBStringLiteralTest.java b/dialect/db/mariadb/src/test/java/org/eclipse/daanse/sql/dialect/db/mariadb/container/MariaDBStringLiteralTest.java new file mode 100644 index 00000000..01f90d9c --- /dev/null +++ b/dialect/db/mariadb/src/test/java/org/eclipse/daanse/sql/dialect/db/mariadb/container/MariaDBStringLiteralTest.java @@ -0,0 +1,71 @@ +/* + * Copyright (c) 2026 Contributors to the Eclipse Foundation. + * + * This program and the accompanying materials are made + * available under the terms of the Eclipse Public License 2.0 + * which is available at https://www.eclipse.org/legal/epl-2.0/ + * + * SPDX-License-Identifier: EPL-2.0 + * + * Contributors: + * SmartCity Jena, Stefan Bischof - initial + */ +package org.eclipse.daanse.sql.dialect.db.mariadb.container; + +import static org.assertj.core.api.Assertions.assertThat; + +import java.sql.Connection; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.sql.Statement; +import java.util.List; + +import org.eclipse.daanse.sql.dialect.api.Dialect; +import org.eclipse.daanse.sql.dialect.api.DialectInitData; +import org.eclipse.daanse.sql.dialect.db.mariadb.MariaDBDialect; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.condition.EnabledIfSystemProperty; +import org.testcontainers.containers.MariaDBContainer; + +/** + * Every value the dialect writes as a string literal is read back by the server as exactly + * that one literal: a quote or a backslash of the value can end no string and start no SQL. + */ +@EnabledIfSystemProperty(named = "integration.docker", matches = "true") +class MariaDBStringLiteralTest { + + static final List VALUES = List.of("a\\", "it's", "a\\' or 1=1 --", "\\\\", "'", "''", "%\\_", + "a\\nb", "tab\there", "x'' or ''1''=''1", "\\'", "' union select 1 -- ", "\u00fcn\u00ef\u00e7\u00f6d\u00e9"); + + @Test + void eachValueIsReadBackAsOneLiteral() throws Exception { + try (MariaDBContainer db = new MariaDBContainer<>("mariadb:11.4")) { + db.start(); + try (Connection c = db.createConnection(""); Statement st = c.createStatement()) { + Dialect dialect = new MariaDBDialect(DialectInitData.fromConnection(c)); + assertThat(dialect.backslashEscapesInStringLiterals()).isTrue(); + for (String value : VALUES) { + assertThat(readBack(st, dialect, value)).isEqualTo(value); + } + // a server that reads a backslash as an ordinary character reads more backslashes, + // and still one literal + st.execute("SET SESSION sql_mode = CONCAT(@@sql_mode, ',NO_BACKSLASH_ESCAPES')"); + for (String value : VALUES) { + assertThat(readBack(st, dialect, value)).isEqualTo(value.replace("\\", "\\\\")); + } + } + } + } + + static String readBack(Statement st, Dialect dialect, String value) throws SQLException { + StringBuilder sql = new StringBuilder("SELECT "); + dialect.quoteStringLiteral(sql, value); + try (ResultSet rs = st.executeQuery(sql.toString())) { + assertThat(rs.getMetaData().getColumnCount()).as(sql.toString()).isEqualTo(1); + assertThat(rs.next()).as(sql.toString()).isTrue(); + String read = rs.getString(1); + assertThat(rs.next()).as(sql.toString()).isFalse(); + return read; + } + } +} diff --git a/dialect/db/mysql/src/main/java/org/eclipse/daanse/sql/dialect/db/mysql/MySqlDialect.java b/dialect/db/mysql/src/main/java/org/eclipse/daanse/sql/dialect/db/mysql/MySqlDialect.java index be3fea04..5f46847e 100644 --- a/dialect/db/mysql/src/main/java/org/eclipse/daanse/sql/dialect/db/mysql/MySqlDialect.java +++ b/dialect/db/mysql/src/main/java/org/eclipse/daanse/sql/dialect/db/mysql/MySqlDialect.java @@ -399,6 +399,11 @@ public boolean allowsCompoundCountDistinct() { return true; } + @Override + public boolean backslashEscapesInStringLiterals() { + return true; + } + @Override public void quoteStringLiteral(StringBuilder buf, String s) { // Go beyond standard singleQuoteString; also quote backslash. diff --git a/dialect/db/mysql/src/test/java/org/eclipse/daanse/sql/dialect/db/mysql/container/MySqlStringLiteralTest.java b/dialect/db/mysql/src/test/java/org/eclipse/daanse/sql/dialect/db/mysql/container/MySqlStringLiteralTest.java new file mode 100644 index 00000000..985c60e9 --- /dev/null +++ b/dialect/db/mysql/src/test/java/org/eclipse/daanse/sql/dialect/db/mysql/container/MySqlStringLiteralTest.java @@ -0,0 +1,71 @@ +/* + * Copyright (c) 2026 Contributors to the Eclipse Foundation. + * + * This program and the accompanying materials are made + * available under the terms of the Eclipse Public License 2.0 + * which is available at https://www.eclipse.org/legal/epl-2.0/ + * + * SPDX-License-Identifier: EPL-2.0 + * + * Contributors: + * SmartCity Jena, Stefan Bischof - initial + */ +package org.eclipse.daanse.sql.dialect.db.mysql.container; + +import static org.assertj.core.api.Assertions.assertThat; + +import java.sql.Connection; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.sql.Statement; +import java.util.List; + +import org.eclipse.daanse.sql.dialect.api.Dialect; +import org.eclipse.daanse.sql.dialect.api.DialectInitData; +import org.eclipse.daanse.sql.dialect.db.mysql.MySqlDialect; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.condition.EnabledIfSystemProperty; +import org.testcontainers.containers.MySQLContainer; + +/** + * Every value the dialect writes as a string literal is read back by the server as exactly + * that one literal: a quote or a backslash of the value can end no string and start no SQL. + */ +@EnabledIfSystemProperty(named = "integration.docker", matches = "true") +class MySqlStringLiteralTest { + + static final List VALUES = List.of("a\\", "it's", "a\\' or 1=1 --", "\\\\", "'", "''", "%\\_", + "a\\nb", "tab\there", "x'' or ''1''=''1", "\\'", "' union select 1 -- ", "\u00fcn\u00ef\u00e7\u00f6d\u00e9"); + + @Test + void eachValueIsReadBackAsOneLiteral() throws Exception { + try (MySQLContainer db = new MySQLContainer<>("mysql:8.4")) { + db.start(); + try (Connection c = db.createConnection(""); Statement st = c.createStatement()) { + Dialect dialect = new MySqlDialect(DialectInitData.fromConnection(c)); + assertThat(dialect.backslashEscapesInStringLiterals()).isTrue(); + for (String value : VALUES) { + assertThat(readBack(st, dialect, value)).isEqualTo(value); + } + // a server that reads a backslash as an ordinary character reads more backslashes, + // and still one literal + st.execute("SET SESSION sql_mode = CONCAT(@@sql_mode, ',NO_BACKSLASH_ESCAPES')"); + for (String value : VALUES) { + assertThat(readBack(st, dialect, value)).isEqualTo(value.replace("\\", "\\\\")); + } + } + } + } + + static String readBack(Statement st, Dialect dialect, String value) throws SQLException { + StringBuilder sql = new StringBuilder("SELECT "); + dialect.quoteStringLiteral(sql, value); + try (ResultSet rs = st.executeQuery(sql.toString())) { + assertThat(rs.getMetaData().getColumnCount()).as(sql.toString()).isEqualTo(1); + assertThat(rs.next()).as(sql.toString()).isTrue(); + String read = rs.getString(1); + assertThat(rs.next()).as(sql.toString()).isFalse(); + return read; + } + } +} diff --git a/dialect/db/postgresql/src/main/java/org/eclipse/daanse/sql/dialect/db/postgresql/PostgreSqlDialect.java b/dialect/db/postgresql/src/main/java/org/eclipse/daanse/sql/dialect/db/postgresql/PostgreSqlDialect.java index 34ef6c6e..d7a84d12 100644 --- a/dialect/db/postgresql/src/main/java/org/eclipse/daanse/sql/dialect/db/postgresql/PostgreSqlDialect.java +++ b/dialect/db/postgresql/src/main/java/org/eclipse/daanse/sql/dialect/db/postgresql/PostgreSqlDialect.java @@ -56,6 +56,21 @@ */ public class PostgreSqlDialect extends AbstractJdbcDialect { + /** + * A plain literal; a value with a backslash as an escape string literal ({@code E'a\\\\b'}). + * A plain literal reads a backslash as an ordinary character only while the server's + * {@code standard_conforming_strings} is on; with it off, {@code \\'} would end no string. + * An escape string literal reads the same with either setting. + */ + @Override + public void quoteStringLiteral(StringBuilder buf, String s) { + if (s != null && s.indexOf('\\') >= 0) { + buf.append("E'").append(s.replace("\\", "\\\\").replace("'", "''")).append('\''); + return; + } + super.quoteStringLiteral(buf, s); + } + /** * Long text is {@code TEXT}; PostgreSQL knows no {@code CLOB} (the CWM structure of Adventure Works DW declares * {@code nvarchar(max)} and {@code xml} as national large objects). A {@code BLOB} is what pgjdbc reads and writes diff --git a/dialect/db/postgresql/src/test/java/org/eclipse/daanse/sql/dialect/db/postgresql/PostgreSqlDialectTest.java b/dialect/db/postgresql/src/test/java/org/eclipse/daanse/sql/dialect/db/postgresql/PostgreSqlDialectTest.java index 00d7f31b..1ab58f1a 100644 --- a/dialect/db/postgresql/src/test/java/org/eclipse/daanse/sql/dialect/db/postgresql/PostgreSqlDialectTest.java +++ b/dialect/db/postgresql/src/test/java/org/eclipse/daanse/sql/dialect/db/postgresql/PostgreSqlDialectTest.java @@ -65,14 +65,14 @@ void testGenerateRegularExpression_CaseInsensitive() throws Exception { String sql = dialect.regexGenerator().generateRegularExpression("table.column", "(?i)|(?u).*a.*").get() .toString(); assertEquals( - "cast(table.column as text) is not null and cast(table.column as text) ~ '(?i)\\A(?:.*a.*)\\Z'", + "cast(table.column as text) is not null and cast(table.column as text) ~ E'(?i)\\\\A(?:.*a.*)\\\\Z'", sql); } @Test void testGenerateRegularExpression_CaseSensitive() throws Exception { String sql = dialect.regexGenerator().generateRegularExpression("table.column", ".*a.*").get().toString(); - assertEquals("cast(table.column as text) is not null and cast(table.column as text) ~ '\\A(?:.*a.*)\\Z'", + assertEquals("cast(table.column as text) is not null and cast(table.column as text) ~ E'\\\\A(?:.*a.*)\\\\Z'", sql); } diff --git a/dialect/db/postgresql/src/test/java/org/eclipse/daanse/sql/dialect/db/postgresql/container/PostgreSqlStringLiteralTest.java b/dialect/db/postgresql/src/test/java/org/eclipse/daanse/sql/dialect/db/postgresql/container/PostgreSqlStringLiteralTest.java new file mode 100644 index 00000000..c1a6c1a2 --- /dev/null +++ b/dialect/db/postgresql/src/test/java/org/eclipse/daanse/sql/dialect/db/postgresql/container/PostgreSqlStringLiteralTest.java @@ -0,0 +1,68 @@ +/* + * Copyright (c) 2026 Contributors to the Eclipse Foundation. + * + * This program and the accompanying materials are made + * available under the terms of the Eclipse Public License 2.0 + * which is available at https://www.eclipse.org/legal/epl-2.0/ + * + * SPDX-License-Identifier: EPL-2.0 + * + * Contributors: + * SmartCity Jena, Stefan Bischof - initial + */ +package org.eclipse.daanse.sql.dialect.db.postgresql.container; + +import static org.assertj.core.api.Assertions.assertThat; + +import java.sql.Connection; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.sql.Statement; +import java.util.List; + +import org.eclipse.daanse.sql.dialect.api.Dialect; +import org.eclipse.daanse.sql.dialect.api.DialectInitData; +import org.eclipse.daanse.sql.dialect.db.postgresql.PostgreSqlDialect; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.condition.EnabledIfSystemProperty; +import org.testcontainers.containers.PostgreSQLContainer; + +/** + * Every value the dialect writes as a string literal is read back by the server as exactly + * that one literal: a quote or a backslash of the value can end no string and start no SQL. + */ +@EnabledIfSystemProperty(named = "integration.docker", matches = "true") +class PostgreSqlStringLiteralTest { + + static final List VALUES = List.of("a\\", "it's", "a\\' or 1=1 --", "\\\\", "'", "''", "%\\_", + "a\\nb", "tab\there", "x'' or ''1''=''1", "\\'", "' union select 1 -- ", "\u00fcn\u00ef\u00e7\u00f6d\u00e9"); + + @Test + void eachValueIsReadBackAsOneLiteral() throws Exception { + try (PostgreSQLContainer db = new PostgreSQLContainer<>("postgres:16-alpine")) { + db.start(); + try (Connection c = db.createConnection(""); Statement st = c.createStatement()) { + Dialect dialect = new PostgreSqlDialect(DialectInitData.fromConnection(c)); + assertThat(dialect.backslashEscapesInStringLiterals()).isFalse(); + for (String setting : List.of("on", "off")) { + st.execute("SET standard_conforming_strings = " + setting); + for (String value : VALUES) { + assertThat(readBack(st, dialect, value)).as(setting).isEqualTo(value); + } + } + } + } + } + + static String readBack(Statement st, Dialect dialect, String value) throws SQLException { + StringBuilder sql = new StringBuilder("SELECT "); + dialect.quoteStringLiteral(sql, value); + try (ResultSet rs = st.executeQuery(sql.toString())) { + assertThat(rs.getMetaData().getColumnCount()).as(sql.toString()).isEqualTo(1); + assertThat(rs.next()).as(sql.toString()).isTrue(); + String read = rs.getString(1); + assertThat(rs.next()).as(sql.toString()).isFalse(); + return read; + } + } +} diff --git a/guard/README.md b/guard/README.md index 4a08e0f5..3e952f76 100644 --- a/guard/README.md +++ b/guard/README.md @@ -26,11 +26,35 @@ configured dialect — or throws a `GuardException`. It rejects, by construction The guard **fails closed**: any unexpected error during validation results in a `GuardException`, never an approved statement. +## Names are written as the database has them + +The guard resolves each schema, table and column of a query against the `DatabaseCatalog` it was +given and writes the statement with the catalog's spelling, quoted by the dialect: +`select * from Foo` on a catalog that names the table `sch.foo` becomes +`SELECT "foo"."id", "foo"."name" FROM "sch"."foo"`. The catalog's names must therefore be the +names the database really uses. + +- A **quoted** name (`"x"`, `` `x` ``, `[x]`) matches only the object with exactly that name. + `SELECT * FROM "FOO"` on a catalog that has only `foo` is refused: whoever quotes a name means + that name. This is how the SQL standard, Oracle, H2, Derby and PostgreSQL treat it. +- An **unquoted** name matches first as the database resolves it, folded by the dialect + (`Dialect.caseFolding()`: upper case on Oracle, H2 and Derby, lower case on PostgreSQL); then as + written; then the one object whose name matches ignoring case. So `select * from foo` also + finds a table the catalog names `FOO`. When objects differ only by case (`foo` and `FOO`) and + none of these picks one, the name is refused as ambiguous. + +This holds in every part of a query: joins and `USING`, subqueries, set operations, derived tables +and CTEs. Every catalog table is written with its schema, also inside subqueries, so the statement +never depends on the connection's default schema. A CTE reference stays a CTE reference, even when a +catalog table has the same name. Columns of a derived table or CTE, and output aliases used in +`ORDER BY`, are written in the case the dialect folds the unquoted alias to; a quoted reference to +them must match that exactly. The dialect is the one the guard is created with; the guard does not +detect it. + ## The function whitelist The whitelist is the control for which functions a query may call. It is a -`List` of **full-match, case-sensitive regular expressions** (evaluated with -`java.util.regex.Pattern.matches`). Every function name appearing anywhere in the +`List` of **full-match regular expressions**. Every function name appearing anywhere in the query — SELECT list, `WHERE`, `HAVING`, subqueries, and so on — must be matched in full by at least one pattern, or the whole statement is rejected with `GuardException("Query has disallowed functions.")`. @@ -45,8 +69,13 @@ Key points: - **An empty list rejects every function** — `List.of()` is the secure default, and the guard is safe out of the box. -- Matching is **case-sensitive and anchored**: `"sum"` matches only `sum`, not `SUM`. - Use `"(?i)sum"`, or list both spellings, when you need case-insensitivity. +- Matching is **anchored**: `"sum"` never matches `summary` or `dbo.sum`. +- An **unquoted** name is matched **case-insensitively**, the way SQL resolves it: + `"sum"` matches `sum(x)`, `SUM(x)` and `Sum(x)`. +- A **quoted** name is matched **exactly, quotes included**: a quoted name is exact in + SQL and may be a different, user-defined function (`"SUM"(x)` on PostgreSQL), so + `"sum"` does not match `"SUM"(x)` or `"sum"(x)`. To allow a quoted call, list it with + its quotes, e.g. `"\"sum\""`. - `List.of(".*")` allows **every** function and is strongly discouraged — see below. ## Keep the whitelist tight diff --git a/guard/api/src/main/java/org/eclipse/daanse/sql/guard/api/SqlGuardFactory.java b/guard/api/src/main/java/org/eclipse/daanse/sql/guard/api/SqlGuardFactory.java index bcda15cb..41f79806 100644 --- a/guard/api/src/main/java/org/eclipse/daanse/sql/guard/api/SqlGuardFactory.java +++ b/guard/api/src/main/java/org/eclipse/daanse/sql/guard/api/SqlGuardFactory.java @@ -28,18 +28,30 @@ public interface SqlGuardFactory { * @param currentSchemaName the schema assumed for unqualified names. * @param databaseCatalog the catalog, schemas, tables and columns that * queries are allowed to reference; anything not - * described here is rejected. + * described here is rejected. Their names are the + * names the database uses: the guard's output writes + * every referenced object with exactly this spelling. + * A quoted name in a query matches only the object with + * exactly that name. An unquoted name matches as the + * dialect folds it, else as written, else the one object + * that matches ignoring case; names that match several + * objects differing only by case are rejected as + * ambiguous. * @param whitelistFunctionsPatterns the functions a query may call, as a list of - * full-match, case-sensitive regular expressions - * (evaluated with {@link java.util.regex.Pattern#matches}). A pattern - * is tested against every function name appearing anywhere in the - * query. A function passes only if at least one pattern matches its - * whole name; a single unmatched function rejects the statement. + * full-match regular expressions. A pattern is tested + * against every function name appearing anywhere in the query. A + * function passes only if at least one pattern matches its whole name; + * a single unmatched function rejects the statement. *
    *
  • An empty list rejects every function — this is * the secure default.
  • - *
  • {@code "sum"} matches only {@code sum}, not {@code SUM}; use - * {@code "(?i)sum"} or list both spellings for case-insensitivity.
  • + *
  • An unquoted function name is matched + * case-insensitively, as SQL resolves it: {@code "sum"} matches + * {@code sum}, {@code SUM} and {@code Sum}.
  • + *
  • A quoted function name is matched exactly, + * quotes included, because a quoted name is exact in SQL and may name + * a different, user-defined function: {@code "sum"} does not match + * {@code "SUM"(x)} or {@code "sum"(x)}.
  • *
  • {@code List.of(".*")} allows every function and is * strongly discouraged: it re-enables side-effecting and * denial-of-service functions (e.g. {@code nextval}, {@code setval}, diff --git a/guard/jsqltranspiler/src/main/java/org/eclipse/daanse/sql/guard/jsqltranspiler/AstWalk.java b/guard/jsqltranspiler/src/main/java/org/eclipse/daanse/sql/guard/jsqltranspiler/AstWalk.java new file mode 100644 index 00000000..13e558c2 --- /dev/null +++ b/guard/jsqltranspiler/src/main/java/org/eclipse/daanse/sql/guard/jsqltranspiler/AstWalk.java @@ -0,0 +1,152 @@ +/* + * Copyright (c) 2026 Contributors to the Eclipse Foundation. + * + * This program and the accompanying materials are made + * available under the terms of the Eclipse Public License 2.0 + * which is available at https://www.eclipse.org/legal/epl-2.0/ + * + * SPDX-License-Identifier: EPL-2.0 + * + * Contributors: + * SmartCity Jena, Stefan Bischof - initial + */ +package org.eclipse.daanse.sql.guard.jsqltranspiler; + +import java.lang.reflect.Array; +import java.lang.reflect.Field; +import java.lang.reflect.Modifier; +import java.util.ArrayDeque; +import java.util.ArrayList; +import java.util.Collection; +import java.util.Collections; +import java.util.Deque; +import java.util.IdentityHashMap; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.function.Consumer; + +import net.sf.jsqlparser.schema.Column; +import net.sf.jsqlparser.statement.select.AllTableColumns; + +/** + * Visits every node of a parsed statement by reading its fields, in a fixed order: the + * fields of each class as it declares them, superclass fields after, the elements of a list + * in their order. It does not follow clauses, so it reaches a node wherever the statement + * puts it, also in a clause no visitor of the parser knows. + * + * It skips what is not part of the statement's text: the parser's own tree, the table the + * resolver attached as resolved, and the table a column or {@code t.*} is qualified by, + * which belongs to that column. + */ +final class AstWalk { + + private static final String MODEL_PACKAGE = "net.sf.jsqlparser."; + private static final String PARSER_PACKAGE = "net.sf.jsqlparser.parser."; + + /** A node that a walk could not read: it cannot be shown to be harmless. */ + static final class UnreadableNodeException extends RuntimeException { + private static final long serialVersionUID = 1L; + + UnreadableNodeException(String type) { + super("the guard cannot read a part of type " + type); + } + } + + private AstWalk() { + } + + /** Each node of the statement once, depth first, in a fixed order. */ + static void walk(Object root, Consumer visitor) { + Set seen = Collections.newSetFromMap(new IdentityHashMap<>()); + Deque todo = new ArrayDeque<>(); + todo.push(root); + while (!todo.isEmpty()) { + Object node = todo.pop(); + if (!seen.add(node)) { + continue; + } + List children = new ArrayList<>(); + if (node instanceof Collection collection) { + collection.stream().filter(o -> o != null).forEach(children::add); + } else if (node instanceof Map map) { + map.values().stream().filter(o -> o != null).forEach(children::add); + } else if (node.getClass().isArray()) { + if (!node.getClass().getComponentType().isPrimitive()) { + for (int i = 0; i < Array.getLength(node); i++) { + Object element = Array.get(node, i); + if (element != null) { + children.add(element); + } + } + } + } else if (isModel(node.getClass())) { + visitor.accept(node); + List> hierarchy = new ArrayList<>(); + for (Class c = node.getClass(); c != null && isModel(c); c = c.getSuperclass()) { + hierarchy.add(c); + } + for (Class c : hierarchy) { + for (Field field : c.getDeclaredFields()) { + if (!skip(node, field)) { + Object value = read(field, node); + if (value != null) { + children.add(value); + } + } + } + } + } else { + continue; + } + // pushed in reverse so that they are visited in their order + for (int i = children.size() - 1; i >= 0; i--) { + todo.push(children.get(i)); + } + } + } + + static boolean isModel(Class type) { + String name = type.getName(); + return name.startsWith(MODEL_PACKAGE) && !name.startsWith(PARSER_PACKAGE); + } + + private static boolean skip(Object node, Field field) { + int modifiers = field.getModifiers(); + if (Modifier.isStatic(modifiers) || Modifier.isTransient(modifiers)) { + return true; + } + Class type = field.getType(); + if (type.isPrimitive() || type == String.class || type.isEnum() + || type.getName().startsWith(PARSER_PACKAGE)) { + return true; + } + String name = field.getName(); + if ("resolvedTable".equals(name)) { + return true; + } + return "table".equals(name) && (node instanceof Column || node instanceof AllTableColumns); + } + + /** A field of a node, read by reflection; a field that cannot be read refuses the statement. */ + static Object read(Field field, Object node) { + try { + field.setAccessible(true); + return field.get(node); + } catch (ReflectiveOperationException | RuntimeException e) { + throw new UnreadableNodeException(node.getClass().getSimpleName()); + } + } + + /** A declared field of a node's class or its superclasses, or {@code null}. */ + static Object field(Object node, String name) { + for (Class c = node.getClass(); c != null && isModel(c); c = c.getSuperclass()) { + try { + return read(c.getDeclaredField(name), node); + } catch (NoSuchFieldException e) { + // look in the superclass + } + } + return null; + } +} diff --git a/guard/jsqltranspiler/src/main/java/org/eclipse/daanse/sql/guard/jsqltranspiler/CanonicalNames.java b/guard/jsqltranspiler/src/main/java/org/eclipse/daanse/sql/guard/jsqltranspiler/CanonicalNames.java new file mode 100644 index 00000000..d4f6457a --- /dev/null +++ b/guard/jsqltranspiler/src/main/java/org/eclipse/daanse/sql/guard/jsqltranspiler/CanonicalNames.java @@ -0,0 +1,241 @@ +/* + * Copyright (c) 2026 Contributors to the Eclipse Foundation. + * + * This program and the accompanying materials are made + * available under the terms of the Eclipse Public License 2.0 + * which is available at https://www.eclipse.org/legal/epl-2.0/ + * + * SPDX-License-Identifier: EPL-2.0 + * + * Contributors: + * SmartCity Jena, Stefan Bischof - initial + */ +package org.eclipse.daanse.sql.guard.jsqltranspiler; + +import java.util.ArrayList; +import java.util.Collection; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Locale; +import java.util.Map; +import java.util.Optional; + +import org.eclipse.daanse.sql.dialect.api.IdentifierCaseFolding; +import org.eclipse.daanse.sql.guard.api.elements.DatabaseCatalog; +import org.eclipse.daanse.sql.guard.api.elements.DatabaseColumn; +import org.eclipse.daanse.sql.guard.api.elements.DatabaseSchema; +import org.eclipse.daanse.sql.guard.api.elements.DatabaseTable; + +/** + * The real names of the schemas, tables and columns a guard may reference, with the + * spelling the database uses. + * + * The resolver library matches names case-insensitively and keeps the query's spelling; + * the database does not. This index answers, for a name as a query wrote it, the name + * as the database has it, so the guard can write every object the way the database + * names it. + * + * Matching rule for one name part: + *
      + *
    • A quoted name ({@code "x"}, {@code `x`}, {@code [x]}) matches only + * the object with exactly that name. If the catalog has the name only in another case, + * the query is refused: whoever quotes a name means that name.
    • + *
    • An unquoted name matches first as the database resolves it, folded + * by the dialect (upper case on Oracle, H2 and Derby, lower case on PostgreSQL); then as + * written; then the single object whose name matches ignoring case. When objects differ + * only by case and none of these picks one, the name is ambiguous and refused.
    • + *
    + * The index holds only what the guard was given, which is what the caller may see, so + * nothing outside the caller's grants can be named through it. + */ +final class CanonicalNames { + + /** A name the guard cannot map to exactly one object. */ + abstract static sealed class NameException extends RuntimeException + permits AmbiguousNameException, QuotedNameMismatchException, NotInCatalogException, + UncheckedPartException { + private static final long serialVersionUID = 1L; + + NameException(String message) { + super(message); + } + } + + /** An unquoted name part that matches several objects differing only by case. */ + static final class AmbiguousNameException extends NameException { + private static final long serialVersionUID = 1L; + + AmbiguousNameException(String kind, String written, Collection candidates) { + super(kind + " " + written + " is ambiguous: " + String.join(", ", candidates)); + } + } + + /** A quoted name part whose object exists only in another case. */ + static final class QuotedNameMismatchException extends NameException { + private static final long serialVersionUID = 1L; + + QuotedNameMismatchException(String kind, String written, Collection candidates) { + super(kind + " " + written + " not found: a quoted name must match exactly, there is only " + + String.join(", ", candidates)); + } + } + + /** A table or column the catalog does not hold: nothing outside it may be named. */ + static final class NotInCatalogException extends NameException { + private static final long serialVersionUID = 1L; + + NotInCatalogException(String kind, String written) { + super(kind + " " + written + " not found in the catalog"); + } + } + + /** + * A part of the statement the guard cannot check against the catalog, such as a table + * function, a {@code TABLE} statement or a star it cannot expand: it is refused. + */ + static final class UncheckedPartException extends NameException { + private static final long serialVersionUID = 1L; + + UncheckedPartException(String part) { + super("the guard cannot check " + part); + } + } + + record TableEntry(String schema, String name, Map> columnsByLowerName) { + } + + private final String currentSchemaName; + private final IdentifierCaseFolding folding; + private final Map> schemasByLowerName = new LinkedHashMap<>(); + /** schema (real spelling) -> lower table name -> tables with that name */ + private final Map>> tables = new LinkedHashMap<>(); + + CanonicalNames(String currentSchemaName, DatabaseCatalog catalog, IdentifierCaseFolding folding) { + this.currentSchemaName = currentSchemaName; + this.folding = folding; + for (DatabaseSchema schema : catalog.getDatabaseSchemas()) { + String schemaName = schema.getName() == null ? "" : schema.getName(); + add(schemasByLowerName, schemaName); + Map> byName = tables.computeIfAbsent(schemaName, k -> new LinkedHashMap<>()); + for (DatabaseTable table : schema.getDatabaseTables()) { + Map> columns = new LinkedHashMap<>(); + for (DatabaseColumn column : table.getDatabaseColumns()) { + add(columns, column.getName()); + } + byName.computeIfAbsent(lower(table.getName()), k -> new ArrayList<>()) + .add(new TableEntry(schemaName, table.getName(), columns)); + } + } + } + + private static void add(Map> index, String name) { + List list = index.computeIfAbsent(lower(name), k -> new ArrayList<>()); + if (!list.contains(name)) { + list.add(name); + } + } + + static String lower(String name) { + return name == null ? "" : name.toLowerCase(Locale.ROOT); + } + + /** A name part as written, without any quote characters ("x", `x`, [x]). */ + static String bare(String written) { + if (written == null) { + return null; + } + return written.replace("\"", "").replace("`", "").replace("[", "").replace("]", ""); + } + + /** Whether a name part was written with quote characters. */ + static boolean isQuoted(String written) { + return written != null && !written.equals(bare(written)); + } + + /** + * The name an alias the query defines is referred to by: an unquoted alias takes the + * case the database folds it to, a quoted one stays as written. + */ + static String aliasReference(IdentifierCaseFolding folding, String alias) { + String bare = bare(alias); + return isQuoted(alias) || folding == null ? bare : folding.fold(bare); + } + + /** + * Whether a name the query wrote refers to an alias the query defines: unquoted, it + * matches ignoring case; quoted, only the alias's exact reference. + */ + static boolean refersToAlias(IdentifierCaseFolding folding, String written, String alias) { + if (written == null || alias == null) { + return false; + } + if (isQuoted(written)) { + return bare(written).equals(aliasReference(folding, alias)); + } + return lower(bare(written)).equals(lower(bare(alias))); + } + + /** + * The single candidate for a written name by the matching rule; empty when there is + * no candidate. The candidates are the names equal to the written one ignoring case. + */ + static Optional pick(IdentifierCaseFolding folding, String kind, String written, + List candidates) { + if (candidates == null || candidates.isEmpty()) { + return Optional.empty(); + } + String name = bare(written); + if (isQuoted(written)) { + if (candidates.contains(name)) { + return Optional.of(name); + } + throw new QuotedNameMismatchException(kind, written, candidates); + } + String folded = folding == null ? name : folding.fold(name); + if (candidates.contains(folded)) { + return Optional.of(folded); + } + if (candidates.contains(name)) { + return Optional.of(name); + } + if (candidates.size() == 1) { + return Optional.of(candidates.get(0)); + } + throw new AmbiguousNameException(kind, written, candidates); + } + + /** The schema as the database names it, for a written schema part. */ + Optional schema(String written) { + return pick(folding, "schema", written, schemasByLowerName.get(lower(bare(written)))); + } + + /** + * The table as the database names it. With a schema part, only that schema is + * searched; without one, the current schema, then a schema-less (unnamed) schema. + */ + Optional table(String writtenSchema, String writtenTable) { + List schemaNames = new ArrayList<>(); + if (writtenSchema != null && !bare(writtenSchema).isEmpty()) { + schema(writtenSchema).ifPresent(schemaNames::add); + } else { + if (currentSchemaName != null) { + schema(currentSchemaName).ifPresent(schemaNames::add); + } + if (tables.containsKey("")) { + schemaNames.add(""); + } + } + for (String schemaName : schemaNames) { + List candidates = tables.getOrDefault(schemaName, Map.of()).get(lower(bare(writtenTable))); + if (candidates == null || candidates.isEmpty()) { + continue; + } + Optional name = pick(folding, "table", writtenTable, + candidates.stream().map(TableEntry::name).toList()); + if (name.isPresent()) { + return candidates.stream().filter(t -> t.name().equals(name.get())).findFirst(); + } + } + return Optional.empty(); + } +} diff --git a/guard/jsqltranspiler/src/main/java/org/eclipse/daanse/sql/guard/jsqltranspiler/DeparserColumResolver.java b/guard/jsqltranspiler/src/main/java/org/eclipse/daanse/sql/guard/jsqltranspiler/DeparserColumResolver.java index 3e8ea19b..f4271709 100644 --- a/guard/jsqltranspiler/src/main/java/org/eclipse/daanse/sql/guard/jsqltranspiler/DeparserColumResolver.java +++ b/guard/jsqltranspiler/src/main/java/org/eclipse/daanse/sql/guard/jsqltranspiler/DeparserColumResolver.java @@ -13,32 +13,70 @@ */ package org.eclipse.daanse.sql.guard.jsqltranspiler; +import java.util.ArrayList; +import java.util.Collections; +import java.util.IdentityHashMap; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.Set; + import org.eclipse.daanse.sql.dialect.api.Dialect; +import org.eclipse.daanse.sql.dialect.api.IdentifierCaseFolding; import org.eclipse.daanse.sql.deparser.api.DialectDeparser; +import org.eclipse.daanse.sql.guard.jsqltranspiler.CanonicalNames.TableEntry; import ai.starlake.transpiler.JSQLColumResolver; import ai.starlake.transpiler.schema.JdbcMetaData; import ai.starlake.transpiler.schema.JdbcResultSetMetaData; import net.sf.jsqlparser.JSQLParserException; +import net.sf.jsqlparser.expression.Alias; +import net.sf.jsqlparser.expression.WindowDefinition; +import net.sf.jsqlparser.expression.WindowElement; +import net.sf.jsqlparser.expression.WindowOffset; +import net.sf.jsqlparser.expression.Expression; +import net.sf.jsqlparser.expression.ExpressionVisitorAdapter; import net.sf.jsqlparser.parser.CCJSqlParserUtil; import net.sf.jsqlparser.schema.Column; import net.sf.jsqlparser.schema.Table; import net.sf.jsqlparser.statement.Statement; +import net.sf.jsqlparser.statement.select.AllColumns; +import net.sf.jsqlparser.statement.select.AllTableColumns; +import net.sf.jsqlparser.statement.select.FromItem; +import net.sf.jsqlparser.statement.select.Join; +import net.sf.jsqlparser.statement.select.Limit; +import net.sf.jsqlparser.statement.select.OrderByElement; +import net.sf.jsqlparser.statement.select.ParenthesedFromItem; +import net.sf.jsqlparser.statement.select.ParenthesedSelect; +import net.sf.jsqlparser.statement.select.PlainSelect; import net.sf.jsqlparser.statement.select.Select; +import net.sf.jsqlparser.statement.select.SelectItem; import net.sf.jsqlparser.statement.select.SelectVisitor; +import net.sf.jsqlparser.statement.select.SetOperationList; +import net.sf.jsqlparser.statement.select.Values; +import net.sf.jsqlparser.statement.select.WithItem; import net.sf.jsqlparser.util.TablesNamesFinder; public class DeparserColumResolver extends JSQLColumResolver { final JdbcMetaData metaData; - private Dialect dialect; - private DialectDeparser dialectDeparser; + private final Dialect dialect; + private final DialectDeparser dialectDeparser; + private final CanonicalNames names; + private Set writtenColumns; public DeparserColumResolver(JdbcMetaData metaData, Dialect dialect, DialectDeparser dialectDeparser) { + this(metaData, dialect, dialectDeparser, null); + } + + DeparserColumResolver(JdbcMetaData metaData, Dialect dialect, DialectDeparser dialectDeparser, + CanonicalNames names) { super(metaData); this.metaData = metaData; this.dialect = dialect; this.dialectDeparser = dialectDeparser; + this.names = names; } /** @@ -58,55 +96,725 @@ public String getResolvedStatementText(String sqlStr) throws JSQLParserException return getResolvedStatementText(statements.get(0)); } + /** + * The columns the query itself wrote, collected before any resolver ran. A column of + * a select list that is not among them was expanded from a {@code *} by the resolver. + */ + void setWrittenColumns(Set writtenColumns) { + this.writtenColumns = writtenColumns; + } + + /** Every column of a statement, by identity. */ + static Set columnsOf(Statement st) { + Set columns = Collections.newSetFromMap(new IdentityHashMap<>()); + new TablesNamesFinder() { + @Override + public Void visit(Column column, S context) { + columns.add(column); + return super.visit(column, context); + } + }.getTables(st); + return columns; + } + /** * Resolves and deparses an already parsed statement, so a caller that has the AST * in hand (the guard, which validated it first) does not pay for a second parse. */ public String getResolvedStatementText(Statement st) { + return getResolvedStatementText(st, () -> { + }); + } + + /** + * As {@link #getResolvedStatementText(Statement)}; {@code afterResolve} runs between + * resolving and writing, to put back what was held out of the resolver. + */ + String getResolvedStatementText(Statement st, Runnable afterResolve) { if (st instanceof Select) { Select select = (Select) st; + // the resolver qualifies every table, CTE references included; remember + // which ones the query wrote without a schema + Set writtenUnqualified = Collections.newSetFromMap(new IdentityHashMap<>()); + new TablesNamesFinder() { + @Override + public Void visit(Table table, S context) { + if (table.getSchemaName() == null) { + writtenUnqualified.add(table); + } + return super.visit(table, context); + } + }.getTables((Statement) select); select.accept((SelectVisitor) this, JdbcMetaData.copyOf(metaData)); - normaliseQualifiers(select); + afterResolve.run(); + new Canonicaliser(writtenUnqualified).statement(select); } + // the statement's own names, written so that every database reads each as one name + WrittenNames.normalize(st, dialect); return dialectDeparser.deparse(st, dialect); } - // The resolvers only ever fill in qualifiers, they never clear them. The connection is - // already scoped to the current catalog, so a table may only be sent schema-qualified. - // Column references keep just the table name or alias: the FROM item carries the schema. - // (JSQLResolver expands "*" with the FROM item's full qualification, JSQLColumResolver - // with the bare name; this normalisation makes both paths emit the same text.) - private void normaliseQualifiers(Select select) { - String currentCatalogName = metaData.getCurrentCatalogName(); - String currentSchemaName = metaData.getCurrentSchemaName(); - new TablesNamesFinder() { + /** + * Writes every catalog object with the name the database gives it, whatever spelling + * the query used, and trims the qualifiers the connection already implies. + * + * The resolver library matches names case-insensitively but keeps the query's + * spelling, and fills in qualifiers without ever replacing them; the deparser quotes + * what the tree holds. This pass walks the statement one SELECT at a time. The FROM + * items of a SELECT are its sources: a catalog table gets its real schema and name, a + * derived table or CTE offers the columns its query returns. A column is then written + * through the source it belongs to, looked up in the SELECT's own sources first and + * then in the enclosing ones, as SQL scopes it. Aliases keep the query's spelling. + * Names are stored unquoted; the deparser quotes them with the dialect's own quote + * character. Column references keep just the table name or alias: the FROM item + * carries the schema, and the connection is scoped to the current catalog. + * + * With a catalog (the guard) the pass is also the guard's own check, independent of + * the resolver library, which does not look at every clause: it walks every clause of + * every SELECT and refuses a table that is neither a catalog table nor a CTE in scope, + * a column no source in scope offers, and a part it cannot check. A table written with + * a schema is never a CTE. A column found in an enclosing SELECT is written with that + * SELECT's table, so the database cannot take it for a column of an inner table the + * catalog does not show. + */ + private final class Canonicaliser { + + /** + * A FROM item: the name it is referred by, the columns it offers, for a CTE the + * name its references are written with, and the qualifier a column the guard + * writes for it takes (the alias, or the CTE's name; none for a catalog table, + * which is written with its schema and name). + */ + private record Source(String key, TableEntry table, boolean aliased, Map> columns, + String reference, String qualifier) { + } + + private static final class Scope { + final Scope parent; + final List sources = new ArrayList<>(); + final Map ctes = new LinkedHashMap<>(); + final Map outputAliases = new LinkedHashMap<>(); + /** The columns a set operation returns, which its ORDER BY may name; else null. */ + List outputColumns; + + Scope(Scope parent) { + this.parent = parent; + } + } + + private final Set
    writtenUnqualified; + /** Columns the resolver expanded from a *: their qualifiers are its own, not the query's. */ + private final Set expanded = Collections.newSetFromMap(new IdentityHashMap<>()); + /** The tables and columns checked against the catalog, by identity. */ + private final Set checked = Collections.newSetFromMap(new IdentityHashMap<>()); + /** With a catalog, anything that cannot be shown to be in it is refused. */ + private final boolean strict = names != null; + private final IdentifierCaseFolding folding = dialect.caseFolding(); + private final String currentCatalogName = metaData.getCurrentCatalogName(); + private final String currentSchemaName = metaData.getCurrentSchemaName(); + + Canonicaliser(Set
    writtenUnqualified) { + this.writtenUnqualified = writtenUnqualified; + } + + /** Canonicalises the whole statement and, with a catalog, checks that nothing escaped. */ + void statement(Select select) { + select(select, null); + if (strict) { + List unchecked = UncheckedParts.of(select, checked); + if (!unchecked.isEmpty()) { + throw new CanonicalNames.UncheckedPartException(unchecked.get(0).toString()); + } + } + } + + /** Canonicalises a query; returns the names of the columns it returns. */ + List select(Select select, Scope outer) { + Scope scope = outer; + if (select.getWithItemsList() != null && !select.getWithItemsList().isEmpty()) { + scope = new Scope(outer); + for (WithItem item : select.getWithItemsList()) { + if (item.getSelect() == null) { + if (strict) { + throw new CanonicalNames.UncheckedPartException("WITH " + item); + } + continue; + } + if (item.isRecursive() && item.getSelect().getSelect() instanceof SetOperationList body + && item.getAlias() != null) { + // the recursive branches read the CTE itself: it offers its anchor's columns + cte(scope, item, select(body.getSelect(0), scope)); + } + cte(scope, item, select(item.getSelect(), scope)); + } + } + if (select instanceof PlainSelect plain) { + return plain(plain, scope); + } + List columns; + if (select instanceof SetOperationList setOperation) { + columns = null; + for (Select branch : setOperation.getSelects()) { + List branchColumns = select(branch, scope); + if (columns == null) { + columns = branchColumns; + } + } + columns = columns == null ? List.of() : columns; + } else if (select instanceof ParenthesedSelect parenthesed && parenthesed.getSelect() != null) { + columns = select(parenthesed.getSelect(), scope); + } else if (select instanceof Values values) { + new ColumnWriter(new Scope(scope)).expression(values.getExpressions()); + columns = List.of(); + } else { + if (strict) { + throw new CanonicalNames.UncheckedPartException(select.getClass().getSimpleName()); + } + return List.of(); + } + tail(select, scope, columns); + return columns; + } + + private void cte(Scope scope, WithItem item, List columns) { + if (item.getWithItemList() != null && !item.getWithItemList().isEmpty()) { + columns = new ArrayList<>(); + for (SelectItem column : item.getWithItemList()) { + // a name the CTE gives its column, not a reference to one + checked.add(column.getExpression()); + columns.add(referenceTo(column.getExpression().toString())); + } + } + if (item.getAlias() != null && item.getAlias().getName() != null) { + String key = CanonicalNames.lower(CanonicalNames.bare(item.getAlias().getName())); + String reference = referenceTo(item.getAlias().getName()); + scope.ctes.put(key, new Source(key, null, true, index(columns), reference, reference)); + } + } + + /** + * ORDER BY, LIMIT, OFFSET and FETCH behind a set operation or a parenthesed + * query: they see the columns it returns, and nothing of its branches. + */ + private void tail(Select select, Scope outer, List outputColumns) { + Scope scope = new Scope(outer); + scope.outputColumns = outputColumns; + ColumnWriter writer = new ColumnWriter(scope); + if (select.getOrderByElements() != null) { + writer.orderBy = true; + for (OrderByElement element : select.getOrderByElements()) { + writer.expression(element.getExpression()); + } + writer.orderBy = false; + } + limits(select, writer); + } + + private void limits(Select select, ColumnWriter writer) { + for (Limit limit : new Limit[] { select.getLimit(), select.getLimitBy() }) { + if (limit != null) { + writer.expression(limit.getRowCount()); + writer.expression(limit.getOffset()); + writer.expression(limit.getByExpressions()); + } + } + if (select.getOffset() != null) { + writer.expression(select.getOffset().getOffset()); + } + if (select.getFetch() != null) { + writer.expression(select.getFetch().getExpression()); + } + } + + private List plain(PlainSelect select, Scope outer) { + Scope scope = new Scope(outer); + List joins = new ArrayList<>(); + fromItem(select.getFromItem(), scope, outer, joins); + if (select.getJoins() != null) { + for (Join join : select.getJoins()) { + fromItem(join.getFromItem(), scope, outer, joins); + joins.add(join); + } + } + List columns = new ArrayList<>(); + for (SelectItem item : select.getSelectItems()) { + if (item.getAlias() != null && item.getAlias().getName() != null) { + scope.outputAliases.put(CanonicalNames.lower(CanonicalNames.bare(item.getAlias().getName())), + item.getAlias().getName()); + } + } + if (strict) { + select.setSelectItems(expandStars(select.getSelectItems(), scope)); + } + ColumnWriter writer = new ColumnWriter(scope); + for (SelectItem item : select.getSelectItems()) { + if (writtenColumns != null && item.getExpression() instanceof Column column + && !writtenColumns.contains(column)) { + expanded.add(column); + } + writer.expression(item.getExpression()); + if (item.getAlias() != null && item.getAlias().getName() != null) { + columns.add(referenceTo(item.getAlias().getName())); + } else if (item.getExpression() instanceof Column column) { + columns.add(column.getColumnName()); + } + } + for (Join join : joins) { + if (join.getOnExpressions() != null) { + join.getOnExpressions().forEach(writer::expression); + } + if (join.getUsingColumns() != null) { + join.getUsingColumns().forEach(writer::expression); + } + } + writer.expression(select.getPreWhere()); + writer.expression(select.getWhere()); + writer.expression(select.getOracleHierarchical()); + if (select.getGroupBy() != null) { + writer.expression(select.getGroupBy().getGroupByExpressionList()); + if (select.getGroupBy().getGroupingSets() != null) { + select.getGroupBy().getGroupingSets().forEach(writer::expression); + } + } + writer.expression(select.getHaving()); + writer.expression(select.getQualify()); + if (select.getDistinct() != null && select.getDistinct().getOnSelectItems() != null) { + for (SelectItem item : select.getDistinct().getOnSelectItems()) { + writer.expression(item.getExpression()); + } + } + if (select.getTop() != null) { + writer.expression(select.getTop().getExpression()); + } + if (select.getWindowDefinitions() != null) { + for (WindowDefinition window : select.getWindowDefinitions()) { + window(window, writer); + } + } + if (select.getOrderByElements() != null) { + writer.orderBy = true; + for (OrderByElement element : select.getOrderByElements()) { + writer.expression(element.getExpression()); + } + writer.orderBy = false; + } + limits(select, writer); + return columns; + } + + private void window(WindowDefinition window, ColumnWriter writer) { + writer.expression(window.getPartitionExpressionList()); + if (window.getOrderByElements() != null) { + for (OrderByElement element : window.getOrderByElements()) { + writer.expression(element.getExpression()); + } + } + WindowElement element = window.getWindowElement(); + if (element != null) { + if (element.getOffset() != null) { + writer.expression(element.getOffset().getExpression()); + } + if (element.getRange() != null) { + for (WindowOffset offset : new WindowOffset[] { element.getRange().getStart(), + element.getRange().getEnd() }) { + if (offset != null) { + writer.expression(offset.getExpression()); + } + } + } + } + } + + private void fromItem(FromItem item, Scope scope, Scope outer, List joins) { + if (item == null) { + return; + } + if (item instanceof Table table) { + table(table, scope); + } else if (item instanceof ParenthesedSelect derived) { + List columns = select(derived, outer); + Alias alias = derived.getAlias(); + if (alias != null && alias.getAliasColumns() != null && !alias.getAliasColumns().isEmpty()) { + columns = alias.getAliasColumns().stream().map(c -> referenceTo(c.name)).toList(); + } + if (alias != null && alias.getName() != null) { + String key = CanonicalNames.lower(CanonicalNames.bare(alias.getName())); + scope.sources.add(new Source(key, null, true, index(columns), null, alias.getName())); + } + } else if (item instanceof ParenthesedFromItem nested) { + int first = scope.sources.size(); + fromItem(nested.getFromItem(), scope, outer, joins); + if (nested.getJoins() != null) { + for (Join join : nested.getJoins()) { + fromItem(join.getFromItem(), scope, outer, joins); + joins.add(join); + } + } + Alias alias = nested.getAlias(); + if (alias != null && alias.getName() != null) { + // a join with an alias offers the columns of the tables it joins + List columns = new ArrayList<>(); + for (Source source : scope.sources.subList(first, scope.sources.size())) { + source.columns().values().forEach(columns::addAll); + } + String key = CanonicalNames.lower(CanonicalNames.bare(alias.getName())); + scope.sources.add(new Source(key, null, true, index(columns), null, alias.getName())); + } + } else if (strict) { + throw new CanonicalNames.UncheckedPartException(item.getClass().getSimpleName() + " " + item); + } + } + + private void table(Table table, Scope scope) { + stripCurrentCatalog(table); + String alias = table.getAlias() == null ? null : table.getAlias().getName(); + if (writtenUnqualified.contains(table)) { + Source cte = cte(scope, table.getName()); + if (cte != null) { + if (CanonicalNames.isQuoted(table.getName()) + && !CanonicalNames.bare(table.getName()).equals(cte.reference())) { + // the resolver took it for the CTE, the database would not + throw new CanonicalNames.QuotedNameMismatchException("table", table.getName(), + List.of(cte.reference())); + } + // a CTE, not a catalog table: the resolver must not have qualified it, + // and the reference is quoted, so it takes the case the CTE's name folds to + table.setSchemaName(null); + table.setDatabaseName(null); + table.setName(cte.reference()); + if (alias == null) { + scope.sources.add(new Source(cte.key(), null, false, cte.columns(), cte.reference(), + cte.reference())); + } else { + String key = CanonicalNames.lower(CanonicalNames.bare(alias)); + scope.sources.add(new Source(key, null, true, cte.columns(), null, alias)); + } + checked.add(table); + return; + } + } + if (names == null) { + return; + } + Optional entry = names.table(table.getSchemaName(), table.getName()); + if (entry.isEmpty()) { + throw new CanonicalNames.NotInCatalogException("table", table.getFullyQualifiedName()); + } + TableEntry found = entry.get(); + table.setName(found.name()); + if (!found.schema().isEmpty()) { + // every catalog table carries its schema, in subqueries too: the statement + // must not depend on the connection's default schema + table.setSchemaName(found.schema()); + } else if (table.getSchemaName() != null) { + table.setSchemaName(CanonicalNames.bare(table.getSchemaName())); + } + String key = CanonicalNames.lower(alias == null ? found.name() : CanonicalNames.bare(alias)); + scope.sources.add(new Source(key, found, alias != null, found.columnsByLowerName(), null, alias)); + checked.add(table); + } + + private Source cte(Scope scope, String name) { + String key = CanonicalNames.lower(CanonicalNames.bare(name)); + for (Scope s = scope; s != null; s = s.parent) { + Source cte = s.ctes.get(key); + if (cte != null) { + return cte; + } + } + return null; + } + + /** + * The stars the resolver left in place (in a subquery of an expression, in a later + * branch of a set operation), written out as the columns the catalog and the query + * give their sources: a star must not reach a column the catalog does not show. + */ + private List> expandStars(List> items, Scope scope) { + List> result = new ArrayList<>(); + for (SelectItem item : items) { + if (!(item.getExpression() instanceof AllColumns star)) { + result.add(item); + continue; + } + if (star.getTransformers() != null && !star.getTransformers().isEmpty()) { + throw new CanonicalNames.UncheckedPartException(star.toString()); + } + List sources = scope.sources; + if (star instanceof AllTableColumns tableStar) { + String key = CanonicalNames.lower(CanonicalNames.bare(tableStar.getTable().getName())); + sources = scope.sources.stream().filter(s -> s.key().equals(key)).limit(1).toList(); + } + if (sources.isEmpty()) { + throw new CanonicalNames.UncheckedPartException(star.toString()); + } + for (Source source : sources) { + if (source.columns().isEmpty()) { + throw new CanonicalNames.UncheckedPartException(star.toString()); + } + for (List spellings : source.columns().values()) { + for (String name : spellings) { + Column column = new Column(); + column.setColumnName(name); + column.setTable(qualifier(source)); + result.add(new SelectItem<>(column)); + } + } + } + } + return result; + } + + /** The table a column the guard writes for a source is qualified with. */ + private Table qualifier(Source source) { + if (source.table() != null && !source.aliased()) { + TableEntry table = source.table(); + return table.schema().isEmpty() ? new Table(table.name()) : new Table(table.schema(), table.name()); + } + return new Table(source.qualifier()); + } + + /** + * How a column the query names by an alias is referred to: an unquoted alias + * takes the case the database folds it to, a quoted one stays as written. + */ + private String referenceTo(String alias) { + return CanonicalNames.aliasReference(folding, alias); + } + + private static Map> index(List columns) { + Map> index = new LinkedHashMap<>(); + for (String column : columns) { + if (column != null) { + List spellings = index.computeIfAbsent(CanonicalNames.lower(column), k -> new ArrayList<>()); + if (!spellings.contains(column)) { + spellings.add(column); + } + } + } + return index; + } + + /** Writes the columns of one SELECT's expressions; subqueries get their own scope. */ + private final class ColumnWriter extends ExpressionVisitorAdapter { + private final Scope scope; + boolean orderBy; + + ColumnWriter(Scope scope) { + this.scope = scope; + } + + void expression(Expression expression) { + if (expression != null) { + expression.accept(this, null); + } + } + @Override - public Void visit(Table table, S context) { - stripCurrentCatalog(table); - return super.visit(table, context); + public Void visit(ParenthesedSelect select, S context) { + Canonicaliser.this.select(select, scope); + return null; + } + + @Override + public Void visit(Select select, S context) { + Canonicaliser.this.select(select, scope); + return null; } @Override public Void visit(Column column, S context) { Table table = column.getTable(); - if (table != null) { - stripCurrentCatalog(table); - if (currentSchemaName != null && !currentSchemaName.isEmpty() - && currentSchemaName.equalsIgnoreCase(table.getUnquotedSchemaName())) { - table.setSchemaName(null); + String qualifier = table == null ? null : table.getName(); + if (qualifier == null || qualifier.isEmpty()) { + unqualified(column); + return null; + } + boolean fromStar = expanded.contains(column); + if (fromStar) { + // the resolver quotes the parts of the qualifiers it writes for a * its + // own way, and breaks quoted names doing so: the qualifier only names the + // FROM item the column came from, whatever its quotes + table.setDatabaseName(CanonicalNames.bare(table.getDatabaseName())); + table.setSchemaName(CanonicalNames.bare(table.getSchemaName())); + table.setName(CanonicalNames.bare(qualifier)); + qualifier = table.getName(); + } + stripCurrentCatalog(table); + Source source = null; + if (table.getSchemaName() == null) { + source = source(CanonicalNames.lower(CanonicalNames.bare(qualifier))); + } else { + if (fromStar) { + source = fromItem(table.getSchemaName(), qualifier); + } + if (source == null && names != null) { + TableEntry entry = names.table(table.getSchemaName(), qualifier).orElse(null); + source = entry == null ? null + : new Source(entry.name(), entry, false, entry.columnsByLowerName(), null, null); } } - return super.visit(column, context); + if (source == null) { + if (strict) { + throw new CanonicalNames.NotInCatalogException("table", table.getFullyQualifiedName()); + } + return null; + } + if (table.getSchemaName() == null && CanonicalNames.isQuoted(qualifier)) { + // a quoted qualifier names its table or CTE exactly; an alias is written + // as the query wrote it and the database resolves it + String exact = source.table() != null && !source.aliased() ? source.table().name() + : source.reference(); + if (exact != null && !CanonicalNames.bare(qualifier).equals(exact)) { + throw new CanonicalNames.QuotedNameMismatchException("table", qualifier, List.of(exact)); + } + } + if (source.table() != null && !source.aliased()) { + table.setName(source.table().name()); + if (table.getSchemaName() != null) { + table.setSchemaName(source.table().schema().isEmpty() + ? CanonicalNames.bare(table.getSchemaName()) + : source.table().schema()); + } + } else if (source.reference() != null) { + table.setName(source.reference()); + } + Optional name = CanonicalNames.pick(folding, "column", column.getColumnName(), + source.columns().get(CanonicalNames.lower(CanonicalNames.bare(column.getColumnName())))); + if (name.isPresent()) { + column.setColumnName(name.get()); + } else if (strict) { + throw new CanonicalNames.NotInCatalogException("column", column.getFullyQualifiedName()); + } + if (currentSchemaName != null && !currentSchemaName.isEmpty() && table.getSchemaName() != null + && currentSchemaName.equalsIgnoreCase(CanonicalNames.bare(table.getSchemaName()))) { + table.setSchemaName(null); + } + checked.add(column); + return null; } - private void stripCurrentCatalog(Table table) { - if (currentCatalogName != null && !currentCatalogName.isEmpty() - && currentCatalogName.equalsIgnoreCase(table.getUnquotedDatabaseName())) { - table.setDatabaseName(null); + /** The catalog table of a FROM item in scope, by schema and name ignoring case. */ + private Source fromItem(String schema, String name) { + for (Scope s = scope; s != null; s = s.parent) { + for (Source source : s.sources) { + if (source.table() != null && source.table().name().equalsIgnoreCase(name) + && source.table().schema().equalsIgnoreCase(schema)) { + return source; + } + } } + return null; + } + + private Source source(String key) { + for (Scope s = scope; s != null; s = s.parent) { + for (Source source : s.sources) { + if (source.key().equals(key)) { + return source; + } + } + } + return null; } - }.getTables((Statement) select); - } + /** + * An unqualified column: in ORDER BY it may name an output column; otherwise + * it belongs to the innermost SELECT whose sources have it, and is written + * when those sources agree on its spelling. + */ + private void unqualified(Column column) { + String written = column.getColumnName(); + if (written == null) { + return; + } + String key = CanonicalNames.lower(CanonicalNames.bare(written)); + String alias = orderBy ? scope.outputAliases.get(key) : null; + if (alias != null && CanonicalNames.refersToAlias(folding, written, alias)) { + // the same test took this entry out of the resolver's sight + // (OutputAliasOrdering): it must name the output column, nothing else + column.setColumnName(CanonicalNames.aliasReference(folding, alias)); + checked.add(column); + return; + } + if (orderBy && scope.outputColumns != null) { + // ORDER BY behind a set operation names a column the set operation returns + Optional output = CanonicalNames.pick(folding, "column", written, + index(scope.outputColumns).get(key)); + if (output.isPresent()) { + column.setColumnName(output.get()); + checked.add(column); + return; + } + } + CanonicalNames.QuotedNameMismatchException mismatch = null; + for (Scope s = scope; s != null; s = s.parent) { + Map spellings = new LinkedHashMap<>(); + int matching = 0; + for (Source source : s.sources) { + try { + Optional spelling = CanonicalNames.pick(folding, "column", written, + source.columns().get(key)); + if (spelling.isPresent()) { + spellings.putIfAbsent(spelling.get(), source); + matching++; + } + } catch (CanonicalNames.AmbiguousNameException e) { + // two columns of one source differ only by case: the query's choice stands + checked.add(column); + return; + } catch (CanonicalNames.QuotedNameMismatchException e) { + // another source may have the quoted name exactly + mismatch = e; + } + } + if (spellings.isEmpty()) { + continue; + } + if (spellings.size() == 1) { + column.setColumnName(spellings.keySet().iterator().next()); + if (strict && s != scope && matching == 1) { + qualifyFromOuter(column, spellings.values().iterator().next(), s); + } + } + // several sources have it: the database refuses it as ambiguous, or + // merges it (USING); either way only catalog columns can answer + checked.add(column); + return; + } + if (mismatch != null) { + throw mismatch; + } + if (strict) { + throw new CanonicalNames.NotInCatalogException("column", written); + } + } + + /** + * A column found in an enclosing SELECT is written with that SELECT's table: + * left bare, the database would take a column of an inner table first, and the + * catalog may not show that inner table all of its columns. If an inner SELECT + * has a source of the same name, the qualifier would name that one: refused. + */ + private void qualifyFromOuter(Column column, Source source, Scope found) { + for (Scope s = scope; s != found; s = s.parent) { + for (Source inner : s.sources) { + if (inner.key().equals(source.key())) { + throw new CanonicalNames.AmbiguousNameException("table", source.key(), + List.of(source.key(), inner.key())); + } + } + } + column.setTable(qualifier(source)); + } + } + + private void stripCurrentCatalog(Table table) { + if (currentCatalogName != null && !currentCatalogName.isEmpty() && table.getDatabaseName() != null + && currentCatalogName.equalsIgnoreCase(CanonicalNames.bare(table.getDatabaseName()))) { + table.setDatabaseName(null); + } + } + } } diff --git a/guard/jsqltranspiler/src/main/java/org/eclipse/daanse/sql/guard/jsqltranspiler/OutputAliasOrdering.java b/guard/jsqltranspiler/src/main/java/org/eclipse/daanse/sql/guard/jsqltranspiler/OutputAliasOrdering.java new file mode 100644 index 00000000..1858a4fe --- /dev/null +++ b/guard/jsqltranspiler/src/main/java/org/eclipse/daanse/sql/guard/jsqltranspiler/OutputAliasOrdering.java @@ -0,0 +1,166 @@ +/* + * Copyright (c) 2026 Contributors to the Eclipse Foundation. + * + * This program and the accompanying materials are made + * available under the terms of the Eclipse Public License 2.0 + * which is available at https://www.eclipse.org/legal/epl-2.0/ + * + * SPDX-License-Identifier: EPL-2.0 + * + * Contributors: + * SmartCity Jena, Stefan Bischof - initial + */ +package org.eclipse.daanse.sql.guard.jsqltranspiler; + +import java.util.ArrayList; +import java.util.List; + +import org.eclipse.daanse.sql.dialect.api.IdentifierCaseFolding; + +import net.sf.jsqlparser.expression.Expression; +import net.sf.jsqlparser.expression.ExpressionVisitorAdapter; +import net.sf.jsqlparser.schema.Column; +import net.sf.jsqlparser.statement.select.FromItem; +import net.sf.jsqlparser.statement.select.Join; +import net.sf.jsqlparser.statement.select.OrderByElement; +import net.sf.jsqlparser.statement.select.ParenthesedFromItem; +import net.sf.jsqlparser.statement.select.ParenthesedSelect; +import net.sf.jsqlparser.statement.select.PlainSelect; +import net.sf.jsqlparser.statement.select.Select; +import net.sf.jsqlparser.statement.select.SelectItem; +import net.sf.jsqlparser.statement.select.SetOperationList; +import net.sf.jsqlparser.statement.select.WithItem; + +/** + * ORDER BY entries that name an output column by its alias ({@code SELECT sum(x) AS total + * ... ORDER BY total}). + * + * The resolver library resolves ORDER BY against the tables only and refuses such an + * alias as an unknown column. SQL resolves an unqualified name in ORDER BY to the output + * column first, and that column is validated with the select list. So these entries are + * taken out while the statement is validated and resolved, and put back before it is + * written. Only a bare, unqualified column name that equals an alias of the same select + * list is taken out; everything else in ORDER BY is validated as before. + */ +final class OutputAliasOrdering { + + private record Detached(PlainSelect select, List original) { + } + + private final List detached = new ArrayList<>(); + private final IdentifierCaseFolding folding; + + private OutputAliasOrdering(IdentifierCaseFolding folding) { + this.folding = folding; + } + + /** + * Takes the alias entries out of every SELECT of the statement. An unquoted entry + * names an alias ignoring case; a quoted one only the alias's exact name, as the + * database folds it. + */ + static OutputAliasOrdering detach(Select select, IdentifierCaseFolding folding) { + OutputAliasOrdering ordering = new OutputAliasOrdering(folding); + ordering.select(select); + return ordering; + } + + /** Puts the entries back, in their original places. */ + void restore() { + for (Detached d : detached) { + d.select().setOrderByElements(d.original()); + } + } + + private void select(Select select) { + if (select == null) { + return; + } + if (select.getWithItemsList() != null) { + for (WithItem item : select.getWithItemsList()) { + select(item.getSelect()); + } + } + if (select instanceof PlainSelect plain) { + plain(plain); + } else if (select instanceof SetOperationList setOperation) { + setOperation.getSelects().forEach(this::select); + } else if (select instanceof ParenthesedSelect parenthesed) { + select(parenthesed.getSelect()); + } + } + + private void plain(PlainSelect select) { + fromItem(select.getFromItem()); + if (select.getJoins() != null) { + for (Join join : select.getJoins()) { + fromItem(join.getFromItem()); + if (join.getOnExpressions() != null) { + join.getOnExpressions().forEach(this::expression); + } + } + } + List aliases = new ArrayList<>(); + for (SelectItem item : select.getSelectItems()) { + expression(item.getExpression()); + if (item.getAlias() != null && item.getAlias().getName() != null) { + aliases.add(item.getAlias().getName()); + } + } + expression(select.getWhere()); + expression(select.getHaving()); + List orderBy = select.getOrderByElements(); + if (orderBy == null || aliases.isEmpty()) { + return; + } + List kept = new ArrayList<>(); + for (OrderByElement element : orderBy) { + if (isAlias(element.getExpression(), aliases)) { + continue; + } + expression(element.getExpression()); + kept.add(element); + } + if (kept.size() != orderBy.size()) { + detached.add(new Detached(select, orderBy)); + select.setOrderByElements(kept.isEmpty() ? null : kept); + } + } + + private boolean isAlias(Expression expression, List aliases) { + return expression instanceof Column column + && (column.getTable() == null || column.getTable().getName() == null) + && column.getColumnName() != null + && aliases.stream().anyMatch(a -> CanonicalNames.refersToAlias(folding, column.getColumnName(), a)); + } + + private void fromItem(FromItem item) { + if (item instanceof ParenthesedSelect derived) { + select(derived.getSelect()); + } else if (item instanceof ParenthesedFromItem nested) { + fromItem(nested.getFromItem()); + if (nested.getJoins() != null) { + nested.getJoins().forEach(join -> fromItem(join.getFromItem())); + } + } + } + + private void expression(Expression expression) { + if (expression == null) { + return; + } + expression.accept(new ExpressionVisitorAdapter() { + @Override + public Void visit(ParenthesedSelect select, S context) { + OutputAliasOrdering.this.select(select.getSelect()); + return null; + } + + @Override + public Void visit(Select select, S context) { + OutputAliasOrdering.this.select(select); + return null; + } + }, null); + } +} diff --git a/guard/jsqltranspiler/src/main/java/org/eclipse/daanse/sql/guard/jsqltranspiler/StatementPolicy.java b/guard/jsqltranspiler/src/main/java/org/eclipse/daanse/sql/guard/jsqltranspiler/StatementPolicy.java new file mode 100644 index 00000000..c47e8c2f --- /dev/null +++ b/guard/jsqltranspiler/src/main/java/org/eclipse/daanse/sql/guard/jsqltranspiler/StatementPolicy.java @@ -0,0 +1,426 @@ +/* + * Copyright (c) 2026 Contributors to the Eclipse Foundation. + * + * This program and the accompanying materials are made + * available under the terms of the Eclipse Public License 2.0 + * which is available at https://www.eclipse.org/legal/epl-2.0/ + * + * SPDX-License-Identifier: EPL-2.0 + * + * Contributors: + * SmartCity Jena, Stefan Bischof - initial + */ +package org.eclipse.daanse.sql.guard.jsqltranspiler; + +import java.util.List; +import java.util.Locale; +import java.util.Map; +import java.util.Set; +import java.util.function.Predicate; +import java.util.regex.Pattern; + +import net.sf.jsqlparser.expression.Alias; +import net.sf.jsqlparser.expression.AllValue; +import net.sf.jsqlparser.expression.AnalyticExpression; +import net.sf.jsqlparser.expression.AnyComparisonExpression; +import net.sf.jsqlparser.expression.ArrayConstructor; +import net.sf.jsqlparser.expression.ArrayExpression; +import net.sf.jsqlparser.expression.BooleanValue; +import net.sf.jsqlparser.expression.CaseExpression; +import net.sf.jsqlparser.expression.CastExpression; +import net.sf.jsqlparser.expression.CollateExpression; +import net.sf.jsqlparser.expression.ConnectByPriorOperator; +import net.sf.jsqlparser.expression.ConnectByRootOperator; +import net.sf.jsqlparser.expression.DateTimeLiteralExpression; +import net.sf.jsqlparser.expression.DateUnitExpression; +import net.sf.jsqlparser.expression.DateValue; +import net.sf.jsqlparser.expression.DoubleValue; +import net.sf.jsqlparser.expression.Expression; +import net.sf.jsqlparser.expression.ExtractExpression; +import net.sf.jsqlparser.expression.Function; +import net.sf.jsqlparser.expression.HexValue; +import net.sf.jsqlparser.expression.IntervalExpression; +import net.sf.jsqlparser.expression.JsonAggregateFunction; +import net.sf.jsqlparser.expression.JsonExpression; +import net.sf.jsqlparser.expression.JsonFunction; +import net.sf.jsqlparser.expression.KeepExpression; +import net.sf.jsqlparser.expression.LongValue; +import net.sf.jsqlparser.expression.MySQLGroupConcat; +import net.sf.jsqlparser.expression.NotExpression; +import net.sf.jsqlparser.expression.NullValue; +import net.sf.jsqlparser.expression.OracleHierarchicalExpression; +import net.sf.jsqlparser.expression.OverlapsCondition; +import net.sf.jsqlparser.expression.Parenthesis; +import net.sf.jsqlparser.expression.RowConstructor; +import net.sf.jsqlparser.expression.RowGetExpression; +import net.sf.jsqlparser.expression.SignedExpression; +import net.sf.jsqlparser.expression.StringValue; +import net.sf.jsqlparser.expression.TimeKeyExpression; +import net.sf.jsqlparser.expression.TimeValue; +import net.sf.jsqlparser.expression.TimestampValue; +import net.sf.jsqlparser.expression.TimezoneExpression; +import net.sf.jsqlparser.expression.TranscodingFunction; +import net.sf.jsqlparser.expression.TrimFunction; +import net.sf.jsqlparser.expression.WhenClause; +import net.sf.jsqlparser.expression.WindowDefinition; +import net.sf.jsqlparser.expression.XMLSerializeExpr; +import net.sf.jsqlparser.expression.operators.arithmetic.Addition; +import net.sf.jsqlparser.expression.operators.arithmetic.BitwiseAnd; +import net.sf.jsqlparser.expression.operators.arithmetic.BitwiseLeftShift; +import net.sf.jsqlparser.expression.operators.arithmetic.BitwiseOr; +import net.sf.jsqlparser.expression.operators.arithmetic.BitwiseRightShift; +import net.sf.jsqlparser.expression.operators.arithmetic.BitwiseXor; +import net.sf.jsqlparser.expression.operators.arithmetic.Concat; +import net.sf.jsqlparser.expression.operators.arithmetic.Division; +import net.sf.jsqlparser.expression.operators.arithmetic.Exponentiation; +import net.sf.jsqlparser.expression.operators.arithmetic.IntegerDivision; +import net.sf.jsqlparser.expression.operators.arithmetic.Modulo; +import net.sf.jsqlparser.expression.operators.arithmetic.Multiplication; +import net.sf.jsqlparser.expression.operators.arithmetic.Subtraction; +import net.sf.jsqlparser.expression.operators.conditional.AndExpression; +import net.sf.jsqlparser.expression.operators.conditional.OrExpression; +import net.sf.jsqlparser.expression.operators.conditional.XorExpression; +import net.sf.jsqlparser.expression.operators.relational.Between; +import net.sf.jsqlparser.expression.operators.relational.ContainedBy; +import net.sf.jsqlparser.expression.operators.relational.Contains; +import net.sf.jsqlparser.expression.operators.relational.EqualsTo; +import net.sf.jsqlparser.expression.operators.relational.ExistsExpression; +import net.sf.jsqlparser.expression.operators.relational.ExpressionList; +import net.sf.jsqlparser.expression.operators.relational.FullTextSearch; +import net.sf.jsqlparser.expression.operators.relational.GreaterThan; +import net.sf.jsqlparser.expression.operators.relational.GreaterThanEquals; +import net.sf.jsqlparser.expression.operators.relational.InExpression; +import net.sf.jsqlparser.expression.operators.relational.IsBooleanExpression; +import net.sf.jsqlparser.expression.operators.relational.IsDistinctExpression; +import net.sf.jsqlparser.expression.operators.relational.IsJsonExpression; +import net.sf.jsqlparser.expression.operators.relational.IsNullExpression; +import net.sf.jsqlparser.expression.operators.relational.IsUnknownExpression; +import net.sf.jsqlparser.expression.operators.relational.JsonOperator; +import net.sf.jsqlparser.expression.operators.relational.LikeExpression; +import net.sf.jsqlparser.expression.operators.relational.Matches; +import net.sf.jsqlparser.expression.operators.relational.MemberOfExpression; +import net.sf.jsqlparser.expression.operators.relational.MinorThan; +import net.sf.jsqlparser.expression.operators.relational.MinorThanEquals; +import net.sf.jsqlparser.expression.operators.relational.NotEqualsTo; +import net.sf.jsqlparser.expression.operators.relational.ParenthesedExpressionList; +import net.sf.jsqlparser.expression.operators.relational.RegExpMatchOperator; +import net.sf.jsqlparser.expression.operators.relational.SimilarToExpression; +import net.sf.jsqlparser.schema.Column; +import net.sf.jsqlparser.schema.Table; +import net.sf.jsqlparser.statement.Statement; +import net.sf.jsqlparser.statement.select.AllColumns; +import net.sf.jsqlparser.statement.select.AllTableColumns; +import net.sf.jsqlparser.statement.select.ParenthesedSelect; +import net.sf.jsqlparser.statement.select.PlainSelect; +import net.sf.jsqlparser.statement.select.SetOperationList; + +/** + * What a statement may contain, decided by the kind of each node before anything is + * resolved. An expression of a kind not listed here is refused: a new syntax of the parser, + * or one of a database, reaches the database only once it is listed. Syntax that calls a + * function or an operator of the database goes through the function whitelist under a fixed + * name. String literals are read here once, by the guard's own rules, so that the dialect + * writes each of them again; a literal form the guard does not read as every database does + * is refused. + */ +final class StatementPolicy { + + /** The most branches one set operation may have. */ + static final int MAX_SET_OPERATION_BRANCHES = 64; + + /** The most FROM items, joins included, one SELECT may have. */ + static final int MAX_FROM_ITEMS = 32; + + /** The most nodes a statement may have. */ + static final int MAX_NODES = 50_000; + + /** A statement the policy refuses. */ + static sealed class RefusedException extends RuntimeException permits DisallowedFunctionException { + private static final long serialVersionUID = 1L; + + RefusedException(String message) { + super(message); + } + } + + /** A call of a function or operator the whitelist does not name. */ + static final class DisallowedFunctionException extends RefusedException { + private static final long serialVersionUID = 1L; + + DisallowedFunctionException(String name) { + super("Query has disallowed functions."); + this.name = name; + } + + final String name; + } + + /** Expressions that read only their operands. */ + private static final Set> PLAIN = Set.of(Column.class, LongValue.class, DoubleValue.class, + HexValue.class, NullValue.class, DateValue.class, TimeValue.class, TimestampValue.class, + BooleanValue.class, AllValue.class, AllColumns.class, AllTableColumns.class, SignedExpression.class, + NotExpression.class, Parenthesis.class, ParenthesedExpressionList.class, ExpressionList.class, + RowConstructor.class, CaseExpression.class, WhenClause.class, AndExpression.class, OrExpression.class, + XorExpression.class, Addition.class, Subtraction.class, Multiplication.class, Division.class, + IntegerDivision.class, Modulo.class, Concat.class, BitwiseAnd.class, BitwiseOr.class, BitwiseXor.class, + BitwiseLeftShift.class, BitwiseRightShift.class, Exponentiation.class, EqualsTo.class, + NotEqualsTo.class, GreaterThan.class, GreaterThanEquals.class, MinorThan.class, MinorThanEquals.class, + Between.class, InExpression.class, ExistsExpression.class, AnyComparisonExpression.class, + IsNullExpression.class, IsBooleanExpression.class, IsDistinctExpression.class, + IsUnknownExpression.class, OverlapsCondition.class, KeepExpression.class, ConnectByPriorOperator.class, + OracleHierarchicalExpression.class, DateUnitExpression.class, PlainSelect.class, + SetOperationList.class, ParenthesedSelect.class, StringValue.class, CastExpression.class, + TimeKeyExpression.class, DateTimeLiteralExpression.class, IntervalExpression.class, + LikeExpression.class, Function.class, AnalyticExpression.class, JsonFunction.class, + JsonAggregateFunction.class); + + /** Syntax that calls a function or operator of the database, by the name the whitelist knows it. */ + private static final Map, String> FUNCTION_LIKE = Map.ofEntries(Map.entry(TrimFunction.class, "trim"), + Map.entry(ExtractExpression.class, "extract"), Map.entry(XMLSerializeExpr.class, "xmlserialize"), + Map.entry(ConnectByRootOperator.class, "connect_by_root"), + Map.entry(TimezoneExpression.class, "at_time_zone"), Map.entry(CollateExpression.class, "collate"), + Map.entry(FullTextSearch.class, "match_against"), Map.entry(Matches.class, "match"), + Map.entry(RegExpMatchOperator.class, "regexp"), Map.entry(SimilarToExpression.class, "similar_to"), + Map.entry(JsonExpression.class, "json_operator"), Map.entry(JsonOperator.class, "json_operator"), + Map.entry(Contains.class, "json_operator"), Map.entry(ContainedBy.class, "json_operator"), + Map.entry(ArrayExpression.class, "array_index"), Map.entry(ArrayConstructor.class, "array"), + Map.entry(RowGetExpression.class, "field_access"), Map.entry(TranscodingFunction.class, "convert"), + Map.entry(MySQLGroupConcat.class, "group_concat"), Map.entry(MemberOfExpression.class, "member_of"), + Map.entry(IsJsonExpression.class, "is_json")); + + /** Types a cast may name: the plain SQL types, without a schema. */ + private static final Set CAST_TYPES = Set.of("int", "integer", "smallint", "bigint", "tinyint", + "mediumint", "int2", "int4", "int8", "decimal", "numeric", "dec", "number", "real", "float", "float4", + "float8", "double", "double precision", "char", "character", "varchar", "character varying", + "varchar2", "nvarchar2", "nchar", "nvarchar", "national character", "national character varying", + "text", "string", "date", "time", "timestamp", "datetime", "datetime2", "timestamptz", + "timestamp with time zone", "timestamp without time zone", "time with time zone", + "time without time zone", "boolean", "bool", "bit", "signed", "unsigned", "signed integer", + "unsigned integer", "binary", "varbinary", "bytea", "uuid", "interval"); + + private static final Set TIME_KEYS = Set.of("CURRENT_DATE", "CURRENT_TIME", "CURRENT_TIMESTAMP", + "LOCALTIME", "LOCALTIMESTAMP"); + + private static final Pattern PLAIN_IDENTIFIER = Pattern.compile("[A-Za-z_][A-Za-z0-9_$]*"); + private static final Pattern DATE_TIME_LITERAL = Pattern.compile("'[0-9 :.+\\-TZ]*'"); + private static final Pattern INTERVAL_PARAMETER = Pattern.compile("'?[0-9A-Za-z :.+\\-]*'?"); + private static final Pattern CAST_ARGUMENT = Pattern.compile("[0-9]+|max|MAX"); + + private final Predicate whitelisted; + private final List disallowed = new java.util.ArrayList<>(); + private int nodes; + + private StatementPolicy(Predicate whitelisted) { + this.whitelisted = whitelisted; + } + + /** + * Checks every node of a statement and reads every string literal once, so that it is + * written by the dialect. + * + * @return the functions and operators the statement calls that the whitelist does not + * name; the caller refuses the statement for them once it has reported the names + * that are not in the catalog, which go first + * @throws RefusedException when the statement holds something else the guard does not allow + */ + static List check(Statement statement, Predicate whitelisted) { + StatementPolicy policy = new StatementPolicy(whitelisted); + AstWalk.walk(statement, policy::node); + return policy.disallowed; + } + + private void node(Object node) { + if (++nodes > MAX_NODES) { + throw new RefusedException("Statement is too large."); + } + if (node instanceof SetOperationList setOperation + && setOperation.getSelects().size() > MAX_SET_OPERATION_BRANCHES) { + throw new RefusedException("Statement has too many set operation branches."); + } + if (node instanceof PlainSelect select) { + int items = (select.getFromItem() != null ? 1 : 0) + + (select.getJoins() != null ? select.getJoins().size() : 0); + if (items > MAX_FROM_ITEMS) { + throw new RefusedException("Statement reads too many tables."); + } + } + if (node instanceof Table table) { + table(table); + } + if (node instanceof WindowDefinition window && window.getWindowName() != null) { + plainIdentifier(window.getWindowName(), "window name"); + } + if (node instanceof Expression expression) { + expression(expression); + } + } + + private void table(Table table) { + @SuppressWarnings("unchecked") + List delimiters = (List) AstWalk.field(table, "partDelimiters"); + if (delimiters != null && delimiters.stream().anyMatch(d -> !".".equals(d))) { + throw new RefusedException("A table name may only be divided by dots."); + } + if (table.getNameParts().stream().anyMatch(part -> part != null && part.indexOf('@') >= 0)) { + throw new RefusedException("A table name may not name a database link."); + } + for (String part : List.of("timeTravelStr", "timeTravelStrAfterAlias", "sampleClause", "pivot", "unpivot", + "mysqlHints", "sqlServerHints")) { + if (AstWalk.field(table, part) != null) { + throw new RefusedException("A table reference may not carry " + part + "."); + } + } + if (Boolean.TRUE.equals(AstWalk.field(table, "tableVariable"))) { + throw new RefusedException("A table variable is not allowed."); + } + Alias alias = table.getAlias(); + if (alias != null && alias.getAliasColumns() != null && !alias.getAliasColumns().isEmpty()) { + throw new RefusedException("A table alias may not rename its columns."); + } + } + + private void expression(Expression expression) { + Class type = expression.getClass(); + String functionLike = FUNCTION_LIKE.get(type); + if (functionLike != null) { + allow(functionLike); + if (expression instanceof ExtractExpression extract) { + plainIdentifier(extract.getName(), "unit of EXTRACT"); + } else if (expression instanceof RowGetExpression rowGet) { + plainIdentifier(rowGet.getColumnName(), "field name"); + } + return; + } + if (!PLAIN.contains(type)) { + throw new RefusedException("The guard does not allow " + type.getSimpleName() + "."); + } + if (expression instanceof StringValue literal) { + literal(literal); + } else if (expression instanceof CastExpression cast) { + cast(cast); + } else if (expression instanceof TimeKeyExpression timeKey) { + String key = timeKey.getStringValue().replace("()", "").trim().toUpperCase(Locale.ROOT); + if (!TIME_KEYS.contains(key)) { + throw new RefusedException("The guard does not allow " + timeKey.getStringValue() + "."); + } + } else if (expression instanceof DateTimeLiteralExpression literal) { + if (literal.getValue() == null || !DATE_TIME_LITERAL.matcher(literal.getValue()).matches()) { + throw new RefusedException("A date or time literal must hold a date or time."); + } + } else if (expression instanceof IntervalExpression interval) { + if (interval.getParameter() != null + && !INTERVAL_PARAMETER.matcher(interval.getParameter()).matches()) { + throw new RefusedException("An interval literal must hold a number and a unit."); + } + if (interval.getIntervalType() != null) { + plainIdentifier(interval.getIntervalType().replace(" ", "_"), "interval unit"); + } + } else if (expression instanceof LikeExpression like) { + switch (like.getLikeKeyWord()) { + case LIKE, ILIKE -> { + } + case SIMILAR_TO -> allow("similar_to"); + case GLOB -> allow("glob"); + case REGEXP, RLIKE, REGEXP_LIKE, MATCH_REGEXP -> allow("regexp"); + default -> allow("match"); + } + } else if (expression instanceof AnalyticExpression analytic) { + allow(analytic.getName()); + if (analytic.getWindowName() != null) { + plainIdentifier(analytic.getWindowName(), "window name"); + } + } else if (expression instanceof Function function) { + allow(function.getName()); + } else if (expression instanceof JsonFunction json) { + allow(json.getType().name()); + } else if (expression instanceof JsonAggregateFunction json) { + allow(json.getType().name()); + } else if (expression instanceof KeepExpression keep) { + if (keep.getName() == null || !"DENSE_RANK".equalsIgnoreCase(keep.getName())) { + throw new RefusedException("KEEP takes DENSE_RANK only."); + } + } + } + + private void allow(String name) { + if (name == null || !whitelisted.test(name)) { + disallowed.add(String.valueOf(name)); + } + } + + private static void plainIdentifier(String name, String what) { + if (name == null || !PLAIN_IDENTIFIER.matcher(name).matches()) { + throw new RefusedException("A " + what + " must be a plain identifier."); + } + } + + /** + * Reads a string literal as the guard parsed it and keeps only its value, which the + * dialect then writes again. A plain literal reads {@code ''} as one quote and a + * backslash as an ordinary character; a dollar-quoted literal reads everything between + * its delimiters. A literal with a prefix the guard does not read as every database does + * ({@code E}, {@code U&}, {@code R}, {@code Q}, a character set) is refused. + */ + private static void literal(StringValue literal) { + String quote = literal.getQuoteStr(); + String prefix = literal.getPrefix(); + String raw = literal.getValue() == null ? "" : literal.getValue(); + String value; + if (quote != null && quote.startsWith("$")) { + if (prefix != null) { + throw new RefusedException("A dollar-quoted literal takes no prefix."); + } + value = raw; + } else if (quote == null || "'".equals(quote)) { + if (prefix == null || "N".equalsIgnoreCase(prefix)) { + value = raw.replace("''", "'"); + } else if ("B".equalsIgnoreCase(prefix) && raw.matches("[01]*")) { + value = raw; + } else { + throw new RefusedException("A string literal with the prefix " + prefix + " is not allowed."); + } + } else { + throw new RefusedException("A string literal in " + quote + " is not allowed."); + } + if (value.indexOf('\u0000') >= 0) { + throw new RefusedException("A string literal may not hold a NUL character."); + } + literal.setValue(value); + literal.setQuoteStr("'"); + if (prefix != null) { + literal.setPrefix(prefix.toUpperCase(Locale.ROOT)); + } + } + + private static void cast(CastExpression cast) { + if (cast.getColDataType() == null) { + throw new RefusedException("A cast must name its type."); + } + var type = cast.getColDataType(); + // the parser keeps the arguments in the type's name: "varchar (10)", "decimal (10, 2)" + String written = type.getDataType() == null ? "" : type.getDataType().trim(); + String name = written; + List arguments = new java.util.ArrayList<>(); + int open = written.indexOf('('); + if (open >= 0) { + if (!written.endsWith(")")) { + throw new RefusedException("A cast to " + type + " is not allowed."); + } + name = written.substring(0, open); + arguments.addAll(List.of(written.substring(open + 1, written.length() - 1).split(","))); + } + if (type.getArgumentsStringList() != null) { + arguments.addAll(type.getArgumentsStringList()); + } + name = name.trim().replaceAll("\\s+", " ").toLowerCase(Locale.ROOT); + if (!CAST_TYPES.contains(name) || type.getCharacterSet() != null + || (type.getArrayData() != null && !type.getArrayData().isEmpty())) { + throw new RefusedException("A cast to " + type + " is not allowed."); + } + for (String argument : arguments) { + if (!CAST_ARGUMENT.matcher(argument.trim()).matches()) { + throw new RefusedException("A cast to " + type + " is not allowed."); + } + } + } +} diff --git a/guard/jsqltranspiler/src/main/java/org/eclipse/daanse/sql/guard/jsqltranspiler/TranspilerSqlGuard.java b/guard/jsqltranspiler/src/main/java/org/eclipse/daanse/sql/guard/jsqltranspiler/TranspilerSqlGuard.java index cfb8f6aa..231fac1b 100644 --- a/guard/jsqltranspiler/src/main/java/org/eclipse/daanse/sql/guard/jsqltranspiler/TranspilerSqlGuard.java +++ b/guard/jsqltranspiler/src/main/java/org/eclipse/daanse/sql/guard/jsqltranspiler/TranspilerSqlGuard.java @@ -61,8 +61,14 @@ public class TranspilerSqlGuard implements SqlGuard { private static final String COULD_NOT_VALIDATE = "Statement could not be validated."; private static final String ONLY_ONE_STATEMENT_IS_PERMITTED = "Only a single statement is permitted."; private static final String STATEMENT_HAS_SIDE_EFFECTS = "Statement has side effects or does not return rows."; + private static final String STATEMENT_TOO_LONG = "Statement is too long."; + private static final String STATEMENT_TOO_DEEP = "Statement is nested too deeply."; + + /** The longest statement text the guard reads, in characters. */ + static final int MAX_STATEMENT_LENGTH = 100_000; private static final Logger LOGGER = LoggerFactory.getLogger(TranspilerSqlGuard.class); private JdbcMetaData jdbcMetaDataToCopy; + private CanonicalNames canonicalNames; private List whitelistFunctionsPatterns = new ArrayList(); private Dialect dialect; private DialectDeparser dialectDeparser; @@ -71,6 +77,7 @@ public TranspilerSqlGuard(String currentCatalogName, String currentSchemaName, D this.whitelistFunctionsPatterns = whitelistFunctionsPatterns; this.dialectDeparser = dialectDeparser; jdbcMetaDataToCopy = calculateMetaData(currentCatalogName, currentSchemaName, databaseCatalog); + canonicalNames = new CanonicalNames(currentSchemaName, databaseCatalog, dialect.caseFolding()); this.dialect = dialect; } @@ -80,11 +87,16 @@ public String guard(String sqlStr) throws GuardException { LOGGER.atInfo().log("guard incoming: {}", sqlStr); - JSQLResolver resolver = new JSQLResolver(jdbcMetaDataToCopy); - if (sqlStr == null || sqlStr.trim().isEmpty()) { throw new EmptyStatementGuardException(); } + if (sqlStr.length() > MAX_STATEMENT_LENGTH) { + throw new GuardException(STATEMENT_TOO_LONG); + } + + // the resolvers write derived tables into the meta data they are given: each + // statement gets its own copy, so that no statement changes what the next may read + JSQLResolver resolver = new JSQLResolver(JdbcMetaData.copyOf(jdbcMetaDataToCopy)); try { // parse the whole input as a script: CCJSqlParserUtil.parse() stops after the @@ -109,6 +121,20 @@ public String guard(String sqlStr) throws GuardException { // case, so reject it explicitly before anything else. validateReadOnly((Select) st); + // what the statement may contain, by the kind of each node; reads every + // string literal once so that the dialect writes it again + List policyDisallowed = StatementPolicy.check(st, this::isWhitelistedFunction); + + // each OVER w gets the definition of w: its expressions are resolved, checked + // and written where they are used + WrittenNames.inlineWindows(st); + + // before any resolver adds columns of its own (it expands every *) + Set writtenColumns = DeparserColumResolver.columnsOf(st); + + // ORDER BY an output alias: the resolver does not know output aliases + OutputAliasOrdering aliasOrdering = OutputAliasOrdering.detach((Select) st, dialect.caseFolding()); + resolver.resolve(st); // select columns should not be empty @@ -153,6 +179,7 @@ public String guard(String sqlStr) throws GuardException { disallowedFunctions.add(function); } } + disallowedFunctions.addAll(policyDisallowed); if (!disallowedFunctions.isEmpty()) { LOGGER.atInfo().log(QUERY_HAS_DISAllOWED_FUNCTIONS); throw new GuardException(QUERY_HAS_DISAllOWED_FUNCTIONS); @@ -167,12 +194,16 @@ public String guard(String sqlStr) throws GuardException { // we can finally resolve for the actually returned columns // on the very same AST that was validated above: no second parse - DeparserColumResolver columResolver = new DeparserColumResolver(jdbcMetaDataToCopy, dialect, - dialectDeparser); + DeparserColumResolver columResolver = new DeparserColumResolver( + JdbcMetaData.copyOf(jdbcMetaDataToCopy), dialect, dialectDeparser, canonicalNames); columResolver.setCommentFlag(false); columResolver.setErrorMode(JdbcMetaData.ErrorMode.STRICT); + columResolver.setWrittenColumns(writtenColumns); + + String rewritten = columResolver.getResolvedStatementText(st, aliasOrdering::restore); - String rewritten = columResolver.getResolvedStatementText(st); + // the text, read again as the database reads it, must hold what was checked + WrittenStatementCheck.check(rewritten, st, dialect); LOGGER.atInfo().log("guard outgoing: {}", rewritten); @@ -187,6 +218,18 @@ public String guard(String sqlStr) throws GuardException { } catch (CatalogNotFoundException | ColumnNotFoundException | SchemaNotFoundException | TableNotDeclaredException | TableNotFoundException ex) { throw new UnresolvableObjectsGuardException(ex.getMessage()); + } catch (StatementPolicy.DisallowedFunctionException ex) { + LOGGER.atInfo().log("{}: {}", QUERY_HAS_DISAllOWED_FUNCTIONS, ex.name); + throw new GuardException(QUERY_HAS_DISAllOWED_FUNCTIONS); + } catch (StatementPolicy.RefusedException | AstWalk.UnreadableNodeException ex) { + LOGGER.atInfo().log(ex.getMessage()); + throw new GuardException(ex.getMessage()); + } catch (StackOverflowError ex) { + // a statement nested too deeply for the parser or a resolver: refused, not thrown + throw new GuardException(STATEMENT_TOO_DEEP); + } catch (CanonicalNames.NameException ex) { + LOGGER.atInfo().log(ex.getMessage()); + throw new UnresolvableObjectsGuardException(ex.getMessage()); } catch (RuntimeException ex) { // Fail closed: any unexpected error while validating untrusted SQL must // deny the statement, never let it through or leak an internal exception. @@ -196,15 +239,33 @@ public String guard(String sqlStr) throws GuardException { } - private boolean isWhitelistedFunction(String function) { - for (String pattern : whitelistFunctionsPatterns) { - if (Pattern.matches(pattern, function)) { + /** + * Whether a function name, as the resolver reports it, is matched in full by a + * whitelist pattern. + * + * SQL resolves an unquoted function name without regard to case: {@code SUM(x)}, + * {@code Sum(x)} and {@code sum(x)} call the same function. A pattern therefore + * matches an unquoted name case-insensitively. A quoted name is exact in SQL and + * may name a different, user-defined function ({@code "SUM"(x)} on PostgreSQL), so + * it keeps the exact, case-sensitive match. The resolver reports quoted names with + * their quotes, which is what tells the two apart. + */ + static boolean isWhitelisted(List patterns, String function) { + boolean quoted = function.indexOf('"') >= 0 || function.indexOf('`') >= 0 || function.indexOf('[') >= 0; + for (String pattern : patterns) { + Pattern compiled = quoted ? Pattern.compile(pattern) + : Pattern.compile(pattern, Pattern.CASE_INSENSITIVE | Pattern.UNICODE_CASE); + if (compiled.matcher(function).matches()) { return true; } } return false; } + private boolean isWhitelistedFunction(String function) { + return isWhitelisted(whitelistFunctionsPatterns, function); + } + private void validateFeatures(Statement st, List allowedFunctions) throws GuardException { // the feature visitor reports function names lower-cased; the whitelist patterns // are case-sensitive, so accept every name the resolver-based check already passed diff --git a/guard/jsqltranspiler/src/main/java/org/eclipse/daanse/sql/guard/jsqltranspiler/UncheckedParts.java b/guard/jsqltranspiler/src/main/java/org/eclipse/daanse/sql/guard/jsqltranspiler/UncheckedParts.java new file mode 100644 index 00000000..f6039806 --- /dev/null +++ b/guard/jsqltranspiler/src/main/java/org/eclipse/daanse/sql/guard/jsqltranspiler/UncheckedParts.java @@ -0,0 +1,136 @@ +/* + * Copyright (c) 2026 Contributors to the Eclipse Foundation. + * + * This program and the accompanying materials are made + * available under the terms of the Eclipse Public License 2.0 + * which is available at https://www.eclipse.org/legal/epl-2.0/ + * + * SPDX-License-Identifier: EPL-2.0 + * + * Contributors: + * SmartCity Jena, Stefan Bischof - initial + */ +package org.eclipse.daanse.sql.guard.jsqltranspiler; + +import java.lang.reflect.Array; +import java.lang.reflect.Field; +import java.lang.reflect.Modifier; +import java.util.ArrayDeque; +import java.util.ArrayList; +import java.util.Collection; +import java.util.Collections; +import java.util.Deque; +import java.util.IdentityHashMap; +import java.util.List; +import java.util.Map; +import java.util.Set; + +import net.sf.jsqlparser.schema.Column; +import net.sf.jsqlparser.schema.Table; +import net.sf.jsqlparser.statement.select.AllTableColumns; + +/** + * The last net of the guard: every table and every column of a statement must have been + * checked against the catalog. + * + * The walks that check names follow the clauses they know. A clause they do not know (a + * new syntax, a dialect's own clause) would carry its tables and columns past them. This + * walk does not follow clauses: it reads every field of the parsed statement, so it finds + * each table and column wherever it sits, and names those no check has seen. + */ +final class UncheckedParts { + + private static final String MODEL_PACKAGE = "net.sf.jsqlparser."; + private static final String PARSER_PACKAGE = "net.sf.jsqlparser.parser."; + + private UncheckedParts() { + } + + /** + * The tables and columns of the statement that are not in {@code checked}. The table a + * column or a {@code t.*} is qualified by is the column's own: it is not a table of + * its own, and is left out. A table the resolver attached as resolved is left out too. + */ + static List of(Object statement, Set checked) { + List unchecked = new ArrayList<>(); + Set seen = Collections.newSetFromMap(new IdentityHashMap<>()); + Deque todo = new ArrayDeque<>(); + todo.push(statement); + while (!todo.isEmpty()) { + Object node = todo.pop(); + if (!seen.add(node)) { + continue; + } + if ((node instanceof Table || node instanceof Column) && !checked.contains(node)) { + unchecked.add(node); + } + if (node instanceof Collection collection) { + collection.stream().filter(o -> o != null).forEach(todo::push); + continue; + } + if (node instanceof Map map) { + map.values().stream().filter(o -> o != null).forEach(todo::push); + continue; + } + Class type = node.getClass(); + if (type.isArray()) { + if (!type.getComponentType().isPrimitive()) { + for (int i = 0; i < Array.getLength(node); i++) { + Object element = Array.get(node, i); + if (element != null) { + todo.push(element); + } + } + } + continue; + } + if (!isModel(type)) { + continue; + } + for (Class c = type; c != null && isModel(c); c = c.getSuperclass()) { + for (Field field : c.getDeclaredFields()) { + if (skip(node, field)) { + continue; + } + Object value = read(field, node); + if (value != null) { + todo.push(value); + } + } + } + } + return unchecked; + } + + private static boolean isModel(Class type) { + String name = type.getName(); + return name.startsWith(MODEL_PACKAGE) && !name.startsWith(PARSER_PACKAGE); + } + + private static boolean skip(Object node, Field field) { + int modifiers = field.getModifiers(); + if (Modifier.isStatic(modifiers) || Modifier.isTransient(modifiers)) { + return true; + } + Class type = field.getType(); + if (type.isPrimitive() || type == String.class || type.isEnum() + || type.getName().startsWith(PARSER_PACKAGE)) { + return true; + } + String name = field.getName(); + if ("resolvedTable".equals(name)) { + return true; + } + return "table".equals(name) && (node instanceof Column || node instanceof AllTableColumns); + } + + private static Object read(Field field, Object node) { + try { + field.setAccessible(true); + return field.get(node); + } catch (ReflectiveOperationException | RuntimeException e) { + // a field that cannot be read cannot be shown to be checked + throw new CanonicalNames.UncheckedPartException(node.getClass().getSimpleName()); + } + } +} diff --git a/guard/jsqltranspiler/src/main/java/org/eclipse/daanse/sql/guard/jsqltranspiler/WrittenNames.java b/guard/jsqltranspiler/src/main/java/org/eclipse/daanse/sql/guard/jsqltranspiler/WrittenNames.java new file mode 100644 index 00000000..c9b1dc05 --- /dev/null +++ b/guard/jsqltranspiler/src/main/java/org/eclipse/daanse/sql/guard/jsqltranspiler/WrittenNames.java @@ -0,0 +1,172 @@ +/* + * Copyright (c) 2026 Contributors to the Eclipse Foundation. + * + * This program and the accompanying materials are made + * available under the terms of the Eclipse Public License 2.0 + * which is available at https://www.eclipse.org/legal/epl-2.0/ + * + * SPDX-License-Identifier: EPL-2.0 + * + * Contributors: + * SmartCity Jena, Stefan Bischof - initial + */ +package org.eclipse.daanse.sql.guard.jsqltranspiler; + +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.regex.Pattern; + +import org.eclipse.daanse.sql.dialect.api.Dialect; +import org.eclipse.daanse.sql.dialect.api.IdentifierQuotingPolicy; + +import net.sf.jsqlparser.expression.Alias; +import net.sf.jsqlparser.expression.AnalyticExpression; +import net.sf.jsqlparser.expression.WindowDefinition; +import net.sf.jsqlparser.schema.Column; +import net.sf.jsqlparser.statement.Statement; +import net.sf.jsqlparser.statement.select.Join; +import net.sf.jsqlparser.statement.select.PlainSelect; + +/** + * The names a statement defines for itself, written so that every database reads each of + * them as one name: aliases of tables, sub queries, common table expressions and output + * columns, the qualifiers that refer to them, and the columns of {@code JOIN ... USING}. + * Named windows are written into the window functions that use them. + */ +final class WrittenNames { + + private static final Pattern PLAIN_IDENTIFIER = Pattern.compile("[A-Za-z_][A-Za-z0-9_$]*"); + + private WrittenNames() { + } + + /** + * Writes each {@code OVER w} with the definition of the window {@code w} and drops the + * {@code WINDOW} clause, so that the window's expressions are written, and checked, where + * they are used. A window defined from another window is refused. + */ + static void inlineWindows(Statement statement) { + AstWalk.walk(statement, node -> { + if (node instanceof PlainSelect select && select.getWindowDefinitions() != null + && !select.getWindowDefinitions().isEmpty()) { + Map windows = new HashMap<>(); + for (WindowDefinition window : select.getWindowDefinitions()) { + if (window.getBaseWindowName() != null) { + throw new StatementPolicy.RefusedException("A window may not be defined from another window."); + } + windows.put(CanonicalNames.lower(window.getWindowName()), window); + } + AstWalk.walk(select, inner -> { + if (inner instanceof AnalyticExpression analytic && analytic.getWindowName() != null) { + WindowDefinition window = windows.get(CanonicalNames.lower(analytic.getWindowName())); + if (window == null) { + throw new StatementPolicy.RefusedException( + "Window " + analytic.getWindowName() + " is not defined."); + } + WindowDefinition inline = new WindowDefinition(); + inline.setPartitionExpressionList(window.getPartitionExpressionList()); + inline.setOrderByElements(window.getOrderByElements()); + inline.setWindowElement(window.getWindowElement()); + analytic.setWindowName(null); + analytic.setWindowDefinition(inline); + } + }); + select.setWindowDefinitions(null); + } + }); + } + + /** Writes the statement's own names as described above, before it is deparsed. */ + static void normalize(Statement statement, Dialect dialect) { + Set aliases = new HashSet<>(); + AstWalk.walk(statement, node -> { + if (node instanceof Alias alias && alias.getName() != null) { + aliases.add(alias.getName()); + } + }); + AstWalk.walk(statement, node -> { + if (node instanceof Alias alias && alias.getName() != null) { + alias.setName(aliasName(alias.getName(), dialect)); + if (alias.getAliasColumns() != null) { + List columns = alias.getAliasColumns().stream() + .map(c -> new Alias.AliasColumn(aliasName(c.name, dialect), c.colDataType)).toList(); + alias.setAliasColumns(new java.util.ArrayList<>(columns)); + } + } else if (node instanceof Join join && join.getUsingColumns() != null) { + for (Column column : join.getUsingColumns()) { + column.setColumnName( + dialect.quoteIdentifierWith(unquoted(column.getColumnName()), IdentifierQuotingPolicy.ALWAYS)); + } + } + }); + // the qualifier of a column names its alias as the declaration does + for (Object qualified : columnsQualifiedByAName(statement)) { + Column column = (Column) qualified; + String name = column.getTable().getName(); + if (aliases.contains(name)) { + column.getTable().setName(aliasName(name, dialect)); + } else { + column.getTable().setName(quoted(name, dialect)); + } + } + // every column name quoted already: the deparser writes a quoted name as it is, and a + // part it prints as the parser does (KEEP, a window frame) then names it quoted too + AstWalk.walk(statement, node -> { + if (node instanceof Column column && column.getColumnName() != null) { + column.setColumnName(quoted(column.getColumnName(), dialect)); + if (column.getTable() != null && column.getTable().getSchemaName() != null) { + column.getTable().setSchemaName(quoted(column.getTable().getSchemaName(), dialect)); + } + } + }); + } + + /** A name quoted by the dialect, once: a name the dialect has quoted already stays as it is. */ + private static String quoted(String name, Dialect dialect) { + return dialect.quoteIdentifierWith(unquoted(name), IdentifierQuotingPolicy.ALWAYS); + } + + private static List columnsQualifiedByAName(Statement statement) { + List columns = new java.util.ArrayList<>(); + AstWalk.walk(statement, node -> { + if (node instanceof Column column && column.getTable() != null && column.getTable().getName() != null + && column.getTable().getSchemaName() == null) { + columns.add(column); + } + }); + return columns; + } + + /** + * An alias as it is written: a plain identifier as the query wrote it, so that it keeps + * its case folding; anything else read without its quotes and quoted by the dialect. + */ + static String aliasName(String name, Dialect dialect) { + if (name == null || PLAIN_IDENTIFIER.matcher(name).matches()) { + return name; + } + return dialect.quoteIdentifierWith(unquoted(name), IdentifierQuotingPolicy.ALWAYS); + } + + /** A name as written without its quotes: {@code "a""b"} is {@code a"b}. */ + static String unquoted(String name) { + if (name == null || name.length() < 2) { + return name; + } + char first = name.charAt(0); + char last = name.charAt(name.length() - 1); + if (first == '"' && last == '"') { + return name.substring(1, name.length() - 1).replace("\"\"", "\""); + } + if (first == '`' && last == '`') { + return name.substring(1, name.length() - 1).replace("``", "`"); + } + if (first == '[' && last == ']') { + return name.substring(1, name.length() - 1).replace("]]", "]"); + } + return name; + } +} diff --git a/guard/jsqltranspiler/src/main/java/org/eclipse/daanse/sql/guard/jsqltranspiler/WrittenStatementCheck.java b/guard/jsqltranspiler/src/main/java/org/eclipse/daanse/sql/guard/jsqltranspiler/WrittenStatementCheck.java new file mode 100644 index 00000000..e3560924 --- /dev/null +++ b/guard/jsqltranspiler/src/main/java/org/eclipse/daanse/sql/guard/jsqltranspiler/WrittenStatementCheck.java @@ -0,0 +1,144 @@ +/* + * Copyright (c) 2026 Contributors to the Eclipse Foundation. + * + * This program and the accompanying materials are made + * available under the terms of the Eclipse Public License 2.0 + * which is available at https://www.eclipse.org/legal/epl-2.0/ + * + * SPDX-License-Identifier: EPL-2.0 + * + * Contributors: + * SmartCity Jena, Stefan Bischof - initial + */ +package org.eclipse.daanse.sql.guard.jsqltranspiler; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; +import java.util.Locale; + +import org.eclipse.daanse.sql.dialect.api.Dialect; +import org.eclipse.daanse.sql.dialect.api.IdentifierQuotingPolicy; + +import net.sf.jsqlparser.JSQLParserException; +import net.sf.jsqlparser.expression.AnalyticExpression; +import net.sf.jsqlparser.expression.Function; +import net.sf.jsqlparser.expression.LongValue; +import net.sf.jsqlparser.expression.StringValue; +import net.sf.jsqlparser.parser.CCJSqlParserUtil; +import net.sf.jsqlparser.schema.Column; +import net.sf.jsqlparser.schema.Table; +import net.sf.jsqlparser.statement.Statement; +import net.sf.jsqlparser.statement.Statements; +import net.sf.jsqlparser.statement.select.PlainSelect; +import net.sf.jsqlparser.statement.select.Select; +import net.sf.jsqlparser.statement.select.SetOperationList; + +/** + * The last check of the guard: the text it is about to return is read again, as the + * database reads it, and must hold what the guard checked and nothing else. The same string + * literals with the same values, the same columns, tables, queries and functions; and every + * column name quoted by the dialect, so that the database resolves the name the guard did. + * + * Whatever wrote a part of the statement without the dialect (a node the deparser prints as + * the parser does, a literal written as the query wrote it) changes how the text reads where + * a quote or a backslash means something else to the database, and is caught here. + */ +final class WrittenStatementCheck { + + private WrittenStatementCheck() { + } + + /** + * @param written the text the guard is about to return + * @param checked the statement the guard checked and deparsed into {@code written} + * @throws StatementPolicy.RefusedException when the text reads otherwise + */ + static void check(String written, Statement checked, Dialect dialect) { + boolean backslash = dialect.backslashEscapesInStringLiterals(); + Statement read; + try { + Statements statements = CCJSqlParserUtil.parseStatements(written, + parser -> parser.withBackslashEscapeCharacter(backslash)); + if (statements == null || statements.size() != 1 || !(statements.get(0) instanceof Select)) { + throw new StatementPolicy.RefusedException("The written statement is not one query."); + } + read = statements.get(0); + } catch (JSQLParserException e) { + throw new StatementPolicy.RefusedException("The written statement cannot be read again."); + } + List expected = parts(checked, false, backslash); + List found = parts(read, true, backslash); + if (!expected.equals(found)) { + throw new StatementPolicy.RefusedException("The written statement does not read as the checked one."); + } + String quote = dialect.quoteIdentifierWith("x", IdentifierQuotingPolicy.ALWAYS).substring(0, 1); + AstWalk.walk(read, node -> { + if (node instanceof Column column && !isQuoted(column.getColumnName(), quote)) { + throw new StatementPolicy.RefusedException( + "The written statement names column " + column.getColumnName() + " unquoted."); + } + }); + } + + private static boolean isQuoted(String name, String quote) { + return name != null && name.length() >= 2 && name.startsWith(quote) + && name.endsWith("[".equals(quote) ? "]" : quote); + } + + /** The parts of a statement that its meaning rests on, sorted. */ + static List parts(Statement statement, boolean asRead, boolean backslash) { + List parts = new ArrayList<>(); + AstWalk.walk(statement, node -> { + if (node instanceof StringValue literal) { + // E'...' is only a way of writing a literal; N and B change its type + String prefix = literal.getPrefix() == null ? "" : literal.getPrefix().toUpperCase(Locale.ROOT); + parts.add("literal " + ("E".equals(prefix) ? "" : prefix) + ":" + + (asRead ? value(literal, backslash) : literal.getValue())); + } else if (node instanceof Column column) { + parts.add("column " + WrittenNames.unquoted(column.getColumnName())); + } else if (node instanceof Table table && table.getName() != null) { + List names = new ArrayList<>(); + for (String part : table.getNameParts()) { + if (part != null && !part.isEmpty()) { + names.add(WrittenNames.unquoted(part)); + } + } + parts.add("table " + String.join(".", names)); + } else if (node instanceof PlainSelect) { + parts.add("select"); + } else if (node instanceof SetOperationList setOperation) { + parts.add("set operation " + setOperation.getSelects().size()); + } else if (node instanceof AnalyticExpression analytic) { + parts.add("function " + CanonicalNames.lower(analytic.getName())); + } else if (node instanceof Function function) { + parts.add("function " + CanonicalNames.lower(function.getName())); + } else if (node instanceof LongValue number) { + parts.add("number " + number.getStringValue()); + } + }); + Collections.sort(parts); + return parts; + } + + /** The value of a literal as the database reads the text the guard wrote. */ + private static String value(StringValue literal, boolean backslash) { + String raw = literal.getValue() == null ? "" : literal.getValue(); + boolean escapes = backslash || "E".equalsIgnoreCase(literal.getPrefix()); + StringBuilder value = new StringBuilder(raw.length()); + for (int i = 0; i < raw.length(); i++) { + char c = raw.charAt(i); + if (c == '\'' && i + 1 < raw.length() && raw.charAt(i + 1) == '\'') { + value.append('\''); + i++; + } else if (escapes && c == '\\' && i + 1 < raw.length() + && (raw.charAt(i + 1) == '\\' || raw.charAt(i + 1) == '\'')) { + value.append(raw.charAt(i + 1)); + i++; + } else { + value.append(c); + } + } + return value.toString(); + } +} diff --git a/guard/jsqltranspiler/src/test/java/org/eclipse/daanse/sql/guard/jsqltranspiler/integration/SqlGuardAttackTest.java b/guard/jsqltranspiler/src/test/java/org/eclipse/daanse/sql/guard/jsqltranspiler/integration/SqlGuardAttackTest.java new file mode 100644 index 00000000..6d9b940e --- /dev/null +++ b/guard/jsqltranspiler/src/test/java/org/eclipse/daanse/sql/guard/jsqltranspiler/integration/SqlGuardAttackTest.java @@ -0,0 +1,472 @@ +/* + * Copyright (c) 2026 Contributors to the Eclipse Foundation. + * + * This program and the accompanying materials are made + * available under the terms of the Eclipse Public License 2.0 + * which is available at https://www.eclipse.org/legal/epl-2.0/ + * + * SPDX-License-Identifier: EPL-2.0 + * + * Contributors: + * SmartCity Jena, Stefan Bischof - initial + */ +package org.eclipse.daanse.sql.guard.jsqltranspiler.integration; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import java.util.ArrayList; +import java.util.List; +import java.util.concurrent.Callable; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.Future; +import java.util.concurrent.TimeUnit; + +import org.eclipse.daanse.sql.dialect.api.Dialect; +import org.eclipse.daanse.sql.dialect.db.h2.H2Dialect; +import org.eclipse.daanse.sql.guard.api.SqlGuard; +import org.eclipse.daanse.sql.guard.api.SqlGuardFactory; +import org.eclipse.daanse.sql.guard.api.elements.DatabaseCatalog; +import org.eclipse.daanse.sql.guard.api.elements.DatabaseColumn; +import org.eclipse.daanse.sql.guard.api.elements.DatabaseSchema; +import org.eclipse.daanse.sql.guard.api.elements.DatabaseTable; +import org.eclipse.daanse.sql.guard.api.exception.GuardException; +import org.junit.jupiter.api.Nested; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.CsvSource; +import org.junit.jupiter.params.provider.ValueSource; +import org.osgi.test.common.annotation.InjectService; + +/** + * Statements a caller must not get past the guard, and statements it must still pass. The catalog + * holds sch.foo(id, name) and sch.fooFact(id, value); every other table, column, function or + * object stands for something the caller may not see or do. A guard either refuses a statement + * or writes one that reads only the catalog, with the meaning the guard checked. + */ +class SqlGuardAttackTest { + + record Column(String getName) implements DatabaseColumn { + } + + record Table(String getName, List getDatabaseColumns) implements DatabaseTable { + } + + record Schema(String getName, List getDatabaseTables) implements DatabaseSchema { + } + + record Catalog(String getName, List getDatabaseSchemas) implements DatabaseCatalog { + } + + static final DatabaseCatalog CATALOG = new Catalog(null, + List.of(new Schema("sch", List.of(new Table("foo", List.of(new Column("id"), new Column("name"))), + new Table("fooFact", List.of(new Column("id"), new Column("value"))))))); + + /** H2 reads a backslash in a string literal as an ordinary character, as the SQL standard does. */ + static final Dialect STANDARD = new H2Dialect(); + + /** + * A database that reads a backslash in a string literal as an escape character, as MySQL, + * MariaDB, ClickHouse and Hive do; it quotes literals as the MySQL dialect does. + */ + static final Dialect BACKSLASH = new H2Dialect() { + @Override + public void quoteStringLiteral(StringBuilder buf, String s) { + buf.append('\'').append(s.replace("'", "''").replace("\\", "\\\\")).append('\''); + } + + @Override + public boolean backslashEscapesInStringLiterals() { + return true; + } + }; + + /** The proven attack: a backslash ends no string for the guard, but for MySQL it does. */ + static final String BACKSLASH_ATTACK = "select id from foo where name = 'a\\' or name = ' union select pw from secret -- '"; + + static SqlGuard guard(SqlGuardFactory factory, Dialect dialect, String... functions) { + return factory.create("", "sch", CATALOG, List.of(functions), dialect); + } + + static void assertRefused(SqlGuard guard, String sql) { + assertThatThrownBy(() -> guard.guard(sql)).as(sql).isInstanceOf(GuardException.class); + } + + @Nested + class StringLiterals { + + @Test + void aBackslashIsAnOrdinaryCharacterForAStandardDatabase(@InjectService SqlGuardFactory factory) + throws Exception { + assertThat(guard(factory, STANDARD).guard(BACKSLASH_ATTACK)).isEqualTo( + "SELECT \"id\" FROM \"sch\".\"foo\" WHERE \"name\" = 'a\\' OR \"name\" = ' union select pw from secret -- '"); + } + + @Test + void aBackslashIsEscapedForADatabaseThatReadsItAsAnEscape(@InjectService SqlGuardFactory factory) + throws Exception { + String written = guard(factory, BACKSLASH).guard(BACKSLASH_ATTACK); + // either the guard reads the statement as that database does and refuses the + // UNION it finds, or it writes both literals so that the database reads two strings + assertThat(written).isEqualTo( + "SELECT \"id\" FROM \"sch\".\"foo\" WHERE \"name\" = 'a\\\\' OR \"name\" = ' union select pw from secret -- '"); + } + + /** + * Every literal is written by the dialect, also inside an expression the deparser + * would otherwise write as the parser printed it. + */ + @ParameterizedTest(name = "{0}") + @ValueSource(strings = { + "select id from foo where name is distinct from 'a\\' or name = ' union select pw from secret -- '", + "select id from foo where name->>'a\\' or name = ' union select pw from secret -- '", + "select id from foo where name #>> 'a\\' or name = ' union select pw from secret -- '", + "select id from foo where name collate \"C\" = 'a\\' or name = ' union select pw from secret -- '", + "select id from foo where name like 'a\\' or name = ' union select pw from secret -- '", + "select id from foo where name like '%a%' escape '\\' or name = ' union select pw from secret -- '", + "select id from foo where name in ('a\\', ' union select pw from secret -- ')", + "select case when name = 'a\\' then ' union select pw from secret -- ' end from foo", + "select max(id) keep (dense_rank first order by 'a\\') from foo where name = ' union select pw from secret -- '", + "select id from foo start with name = 'a\\' connect by prior id = id and name = ' union select pw from secret -- '" }) + void noLiteralIsWrittenAsTheQueryWroteIt(String sql, @InjectService SqlGuardFactory factory) { + SqlGuard guard = guard(factory, BACKSLASH, "max", "collate", "json_operator"); + String written; + try { + written = guard.guard(sql); + } catch (GuardException refused) { + return; + } + assertThat(written).as(sql).doesNotContain("'a\\'").doesNotContain("'\\'"); + } + + @Test + void anEscapedQuoteKeepsItsValue(@InjectService SqlGuardFactory factory) throws Exception { + assertThat(guard(factory, STANDARD).guard("select id from foo where name = 'it''s'")) + .isEqualTo("SELECT \"id\" FROM \"sch\".\"foo\" WHERE \"name\" = 'it''s'"); + assertThat(guard(factory, BACKSLASH).guard("select id from foo where name = 'x'' or 1=1 --'")) + .isEqualTo("SELECT \"id\" FROM \"sch\".\"foo\" WHERE \"name\" = 'x'' or 1=1 --'"); + } + + @Test + void aDollarQuotedStringIsWrittenAsAPlainLiteral(@InjectService SqlGuardFactory factory) + throws Exception { + assertThat(guard(factory, STANDARD).guard("select id from foo where name = $$a'b$$")) + .isEqualTo("SELECT \"id\" FROM \"sch\".\"foo\" WHERE \"name\" = 'a''b'"); + assertThat(guard(factory, BACKSLASH).guard("select id from foo where name = $$a\\' union select pw from secret -- $$")) + .isEqualTo("SELECT \"id\" FROM \"sch\".\"foo\" WHERE \"name\" = 'a\\\\'' union select pw from secret -- '"); + } + + /** Forms whose reading depends on the database are refused rather than guessed. */ + @ParameterizedTest(name = "{0}") + @ValueSource(strings = { "select id from foo where name = E'a\\' or 1=1 --'", + "select id from foo where name = q'[a' or 1=1 --]'", "select id from foo where name = _utf8'a'", + "select id from foo where name = r'a\\b'", "select id from foo where name = U&'\\0061'", + "select id from foo where id = B'12'", "select id from foo where name = 'a\u0000b'" }) + void aLiteralTheGuardCannotReadAsTheDatabaseDoesIsRefused(String sql, + @InjectService SqlGuardFactory factory) { + assertRefused(guard(factory, STANDARD), sql); + assertRefused(guard(factory, BACKSLASH), sql); + } + + @ParameterizedTest(name = "{0}") + @CsvSource(delimiter = '|', value = { + "select id from foo where name = N'x'|SELECT \"id\" FROM \"sch\".\"foo\" WHERE \"name\" = N'x'", + "select id from foo where id = B'101'|SELECT \"id\" FROM \"sch\".\"foo\" WHERE \"id\" = B'101'", + "select id from foo where name = X'41'|SELECT \"id\" FROM \"sch\".\"foo\" WHERE \"name\" = X'41'", + "select id from foo where name = 'a' and name <> ''|SELECT \"id\" FROM \"sch\".\"foo\" WHERE \"name\" = 'a' AND \"name\" <> ''" }) + void plainLiteralForms(String sql, String expected, @InjectService SqlGuardFactory factory) + throws Exception { + assertThat(guard(factory, STANDARD).guard(sql)).isEqualTo(expected); + } + } + + @Nested + class SideEffectsAndSessionState { + + @ParameterizedTest(name = "{0}") + @ValueSource(strings = { "select next value for seq from foo", "select seq.nextval from foo", + "select @@version from foo", "select @@datadir from foo", "select @x := id from foo", + "select @a from foo", "select $1 from foo", "select id from foo where id = ?", + "select id from foo where id = :p", "select id into newtab from foo", + "select id from foo into outfile '/tmp/x'", "select id from foo for update", + "select id from foo for share skip locked" }) + void refused(String sql, @InjectService SqlGuardFactory factory) { + assertRefused(guard(factory, STANDARD, "sum", "count", "max"), sql); + } + } + + @Nested + class Casts { + + @ParameterizedTest(name = "{0}") + @ValueSource(strings = { "select cast('secret' as regclass) from foo", "select 'secret'::regclass from foo", + "select 'secret'::regrole from foo", "select cast(name as secretschema.secrettype) from foo", + "select try_cast(name as regclass) from foo" }) + void aTypeOutsideThePlainSqlTypesIsRefused(String sql, @InjectService SqlGuardFactory factory) { + assertRefused(guard(factory, STANDARD), sql); + } + + @ParameterizedTest(name = "{0}") + @ValueSource(strings = { "select cast(id as varchar(10)) from foo", "select id::int from foo", + "select cast(name as integer) from foo", "select cast(id as decimal(10, 2)) from foo" }) + void aCastToAPlainTypePasses(String sql, @InjectService SqlGuardFactory factory) throws Exception { + assertThat(guard(factory, STANDARD).guard(sql)).contains("\"sch\".\"foo\""); + } + } + + /** + * Syntax that calls a function or an operator of the database is refused unless the + * whitelist names it; an empty whitelist refuses every such call. + */ + @Nested + class FunctionLikeSyntax { + + @ParameterizedTest(name = "{0}") + @ValueSource(strings = { "select trim(name) from foo", "select extract(year from name) from foo", + "select xmlserialize(content name as text) from foo", + "select connect_by_root id from foo start with id = 1 connect by prior id = id", + "select id at time zone 'UTC' from foo", "select name collate \"C\" from foo", + "select id from foo where match (name) against ('a')", "select id from foo where name ~ '(a+)+$'", + "select id from foo where name regexp '(a+)+$'", "select id from foo where name rlike 'a'", + "select id from foo where name similar to 'a'", "select name->>'a' from foo", + "select name #>> '{a}' from foo", "select id[1] from foo", "select (name).field from foo", + "select substring(name from 1 for 2) from foo", "select convert(name using utf8) from foo", + "select position('a' in name) from foo", "select array[id] from foo" }) + void anEmptyWhitelistRefusesIt(String sql, @InjectService SqlGuardFactory factory) { + assertRefused(guard(factory, STANDARD), sql); + } + + @ParameterizedTest(name = "{1}: {0}") + @CsvSource(delimiter = '|', value = { "select trim(name) from foo|trim", + "select extract(year from name) from foo|extract", "select name collate \"C\" from foo|collate", + "select id from foo where name ~ 'a'|regexp", "select id from foo where name regexp 'a'|regexp", + "select id from foo where name similar to 'a'|similar_to", "select name->>'a' from foo|json_operator", + "select id at time zone 'UTC' from foo|at_time_zone" }) + void theWhitelistAllowsItByName(String sql, String name, @InjectService SqlGuardFactory factory) + throws Exception { + assertThat(guard(factory, STANDARD, name).guard(sql)).contains("\"sch\".\"foo\""); + } + } + + /** What the guard writes names each object as the catalog does, quoted by the dialect. */ + @Nested + class NamesAreWrittenAsChecked { + + @ParameterizedTest(name = "{0}") + @CsvSource(delimiter = '|', value = { + "select ID collate \"C\" from foo|collate|SELECT \"id\" COLLATE \"C\" FROM \"sch\".\"foo\"", + "select max(id) keep (dense_rank first order by NAME) from foo|max|SELECT max(\"id\") KEEP (dense_rank FIRST ORDER BY \"name\") FROM \"sch\".\"foo\"", + "select sum(id) over w from foo window w as (partition by NAME)|sum|SELECT sum(\"id\") OVER (PARTITION BY \"name\" ) FROM \"sch\".\"foo\"", + "select id from foo where name is distinct from 'a'||SELECT \"id\" FROM \"sch\".\"foo\" WHERE \"name\" IS DISTINCT FROM 'a'", + "select id from foo start with id = 1 connect by prior id = id||SELECT \"id\" FROM \"sch\".\"foo\" START WITH \"id\" = 1 CONNECT BY PRIOR \"id\" = \"id\"", + "select id from foo order by NAME collate \"C\"|collate|SELECT \"id\" FROM \"sch\".\"foo\" ORDER BY \"name\" COLLATE \"C\"", + "select NAME->>'a' from foo|json_operator|SELECT \"name\" ->> 'a' FROM \"sch\".\"foo\"" }) + void eachNameIsQuoted(String sql, String function, String expected, @InjectService SqlGuardFactory factory) + throws Exception { + SqlGuard guard = function == null ? guard(factory, STANDARD) : guard(factory, STANDARD, function); + assertThat(guard.guard(sql)).isEqualTo(expected); + } + + /** An alias is one name: it is written so that every database reads it as one. */ + @ParameterizedTest(name = "{0}") + @CsvSource(delimiter = '|', value = { + "select id as `x\" , (select 1) as \"y` from foo|SELECT \"id\" AS \"x\"\" , (select 1) as \"\"y\" FROM \"sch\".\"foo\"", + "select id as \"x\"\" from secret --\" from foo|SELECT \"id\" AS \"x\"\" from secret --\" FROM \"sch\".\"foo\"", + "select id as k from foo|SELECT \"id\" AS k FROM \"sch\".\"foo\"" }) + void anAliasIsWrittenAsOneName(String sql, String expected, @InjectService SqlGuardFactory factory) + throws Exception { + assertThat(guard(factory, STANDARD).guard(sql)).isEqualTo(expected); + } + } + + /** One guard serves many statements: none of them changes what the next one may read. */ + @Nested + class OneGuardManyStatements { + + @Test + void aDerivedTableDoesNotChangeTheCatalog(@InjectService SqlGuardFactory factory) throws Exception { + SqlGuard guard = guard(factory, STANDARD); + assertThat(guard.guard("select value from fooFact")).isEqualTo("SELECT \"value\" FROM \"sch\".\"fooFact\""); + guard.guard("select fooFact.x from (select id as x from foo) fooFact"); + assertThat(guard.guard("select value from fooFact")).isEqualTo("SELECT \"value\" FROM \"sch\".\"fooFact\""); + assertThat(guard.guard("select * from fooFact")) + .isEqualTo("SELECT \"fooFact\".\"id\", \"fooFact\".\"value\" FROM \"sch\".\"fooFact\""); + } + + @Test + void manyThreadsShareOneGuard(@InjectService SqlGuardFactory factory) throws Exception { + SqlGuard guard = guard(factory, STANDARD, "count"); + String[] statements = { "select value from fooFact", "select fooFact.x from (select id as x from foo) fooFact", + "select count(*) from foo where name = 'a'", "with c as (select id from foo) select id from c" }; + String[] expected = new String[statements.length]; + for (int i = 0; i < statements.length; i++) { + expected[i] = guard(factory, STANDARD, "count").guard(statements[i]); + } + ExecutorService pool = Executors.newFixedThreadPool(8); + try { + List> tasks = new ArrayList<>(); + for (int t = 0; t < 8; t++) { + int offset = t; + tasks.add(() -> { + for (int r = 0; r < 100; r++) { + int i = (r + offset) % statements.length; + assertThat(guard.guard(statements[i])).isEqualTo(expected[i]); + } + return null; + }); + } + for (Future f : pool.invokeAll(tasks, 2, TimeUnit.MINUTES)) { + f.get(); + } + } finally { + pool.shutdownNow(); + } + } + } + + /** A statement too large or too deep is refused with a GuardException, quickly. */ + @Nested + class Limits { + + @Test + void manyTermsAreRefusedNotThrown(@InjectService SqlGuardFactory factory) { + StringBuilder sql = new StringBuilder("select id from foo where id = 0"); + for (int i = 0; i < 20000; i++) { + sql.append(" or id = ").append(i); + } + long start = System.nanoTime(); + assertRefused(guard(factory, STANDARD), sql.toString()); + assertThat(TimeUnit.NANOSECONDS.toSeconds(System.nanoTime() - start)).isLessThan(10); + } + + @Test + void manyBranchesAreRefused(@InjectService SqlGuardFactory factory) { + StringBuilder sql = new StringBuilder("select id from foo"); + for (int i = 0; i < 2000; i++) { + sql.append(" union all select id from foo"); + } + assertRefused(guard(factory, STANDARD), sql.toString()); + } + + @Test + void aHugeStatementIsRefused(@InjectService SqlGuardFactory factory) { + assertRefused(guard(factory, STANDARD), "select id from foo where name = '" + "a".repeat(1_000_000) + "'"); + } + + @Test + void manyTablesAreRefused(@InjectService SqlGuardFactory factory) { + StringBuilder sql = new StringBuilder("select f0.id from foo f0"); + for (int i = 1; i < 100; i++) { + sql.append(", foo f").append(i); + } + assertRefused(guard(factory, STANDARD), sql.toString()); + } + + @Test + void ordinarySizesPass(@InjectService SqlGuardFactory factory) throws Exception { + StringBuilder ors = new StringBuilder("select id from foo where id = 0"); + for (int i = 1; i < 50; i++) { + ors.append(" or id = ").append(i); + } + StringBuilder unions = new StringBuilder("select id from foo"); + for (int i = 0; i < 10; i++) { + unions.append(" union all select id from fooFact"); + } + SqlGuard guard = guard(factory, STANDARD); + guard.guard(ors.toString()); + guard.guard(unions.toString()); + guard.guard("select a.id from foo a, foo b, foo c, fooFact d"); + } + } + + /** A table reference the guard would write without a part the query gave is refused. */ + @Nested + class TableReferences { + + @ParameterizedTest(name = "{0}") + @ValueSource(strings = { "select * from foo@remote", "select id from foo with (nolock)", + "select id from foo partition (p0)", "select id from foo as of timestamp '2020-01-01'", + "select * from foo as f(a, b)", "select a from foo as f(a, b)" }) + void refused(String sql, @InjectService SqlGuardFactory factory) { + assertRefused(guard(factory, STANDARD), sql); + } + } + + /** Statements that are not one plain query. */ + @Nested + class StatementKinds { + + @ParameterizedTest(name = "{0}") + @ValueSource(strings = { "explain analyze select id from foo", "show tables", "select id from foo; select 1", + "values (1)", "table foo", "select id from foo union table secret" }) + void refused(String sql, @InjectService SqlGuardFactory factory) { + assertRefused(guard(factory, STANDARD), sql); + } + } + + /** Names that reach beyond the catalog, wherever the statement puts them. */ + @Nested + class NamesOutsideTheCatalog { + + @ParameterizedTest(name = "{0}") + @ValueSource(strings = { "select * from secretdb.sch.foo", "select secretdb.sch.foo.id from secretdb.sch.foo", + "select * from srv.secretdb.sch.foo", "select rowid, rownum from foo", "select ctid from foo", + "select current_user from foo", "select session_user from foo", "select user from foo", + "select 1 from dual", "select \"select\" from foo", + "select id from foo where id in (select x from secret)", + "select id from foo limit (select x from secret)", + "select id from foo limit (select 1 from secret where pw > 'm')", + "select id from foo offset (select x from secret) rows", + "select id from foo fetch first (select x from secret) rows only", + "select id from foo qualify (select x from secret) = 1", + "select id, sum(id) over w from foo window w as (order by (select x from secret))", + "select distinct on ((select x from secret)) id from foo", + "select id from foo union select id from fooFact order by (select x from secret)", + "select id from foo union select id from fooFact limit (select x from secret)", + "select id from foo union select id from fooFact order by secret_col", + "select count(*) filter (where id in (select x from secret)) from foo", + "with foo as (select value as hidden from fooFact) select hidden from sch.foo", + "with foo as (select value as hidden from fooFact) select foo.hidden from sch.foo", + "select x.hidden from sch.foo x", "select id from foo where exists (select * from secret)", + "select id from foo where exists (select 1 from fooFact where hidden = 1)", + "select * from foo pivot (count(id) for name in ('a'))", + "select id from foo unpivot (v for k in (name))", + "select id from foo, lateral (select x from secret) s", + "select id from foo, json_table(name, '$' columns (a int path '$.a')) jt", + "select id from foo, table(secret_fn()) t", "select id from foo, generate_series(1, 3) g", + "select id from foo, unnest(array[1, 2]) u" }) + void refused(String sql, @InjectService SqlGuardFactory factory) { + assertRefused(guard(factory, STANDARD, "count", "max", "sum"), sql); + } + } + + /** Statements that read only the catalog pass. */ + @Nested + class StillAllowed { + + @ParameterizedTest(name = "{0}") + @ValueSource(strings = { "select distinct id from foo", "select all id from foo", + "select count(distinct id) from foo", "select count(*) from foo having count(*) > 1", + "select id from foo fetch first 1 rows with ties", "select id from foo limit 10 offset 5", + "select case when exists (select 1 from fooFact) then 1 end from foo", + "select not exists (select 1 from fooFact) from foo", + "select (select max(id) from fooFact) from foo", + "select id from foo where id = any (select id from fooFact)", + "select id from foo where (id, name) in (select id, value from fooFact)", + "select id from foo f where f.id = (select max(g.id) from foo g where g.name = f.name)", + "select id from foo natural join fooFact", "select foo.name from foo full join fooFact using (id)", + "select -id, +id, id || name, id % 2 from foo", "select id from foo group by grouping sets ((id), ())", + "select id from foo where name like '%a%'", "select id from foo where name is distinct from 'a'", + "select sum(id) over (partition by name order by id) from foo", + "select id as k from foo order by k", "select id from foo union select id from fooFact order by id", + "with c as (select id from foo) select c.id from c join fooFact on c.id = fooFact.id", + "select id from foo where id in (1, 2, 3) and name is not null", "select 1", + "select id from foo where exists (select 1)", + "select current_date, current_timestamp from foo", "select cast(id as varchar(10)) from foo", + "select id from foo where id between 1 and 5" }) + void passes(String sql, @InjectService SqlGuardFactory factory) throws Exception { + assertThat(guard(factory, STANDARD, "count", "max", "sum").guard(sql)).isNotBlank(); + } + } +} diff --git a/guard/jsqltranspiler/src/test/java/org/eclipse/daanse/sql/guard/jsqltranspiler/integration/SqlGuardTest.java b/guard/jsqltranspiler/src/test/java/org/eclipse/daanse/sql/guard/jsqltranspiler/integration/SqlGuardTest.java index 97559a26..41b20ec1 100644 --- a/guard/jsqltranspiler/src/test/java/org/eclipse/daanse/sql/guard/jsqltranspiler/integration/SqlGuardTest.java +++ b/guard/jsqltranspiler/src/test/java/org/eclipse/daanse/sql/guard/jsqltranspiler/integration/SqlGuardTest.java @@ -131,26 +131,17 @@ public class SqlGuardTest { select * from foo where foo.id in (select fooFact.id from fooFact)"""; private static final String SQL_WITH_IN_EXPECTED = """ - SELECT "foo"."id", "foo"."name" FROM "sch"."foo" WHERE "foo"."id" IN (SELECT "fooFact"."id" FROM "fooFact")"""; + SELECT "foo"."id", "foo"."name" FROM "sch"."foo" WHERE "foo"."id" IN (SELECT "fooFact"."id" FROM "sch"."fooFact")"""; private static final String TRIPLE_SELECT_SQL = """ SELECT * FROM ( SELECT * FROM ( SELECT * FROM foo inner join fooFact on foo.id = fooFact.id ) a ) b"""; - private static final String TRIPLE_SELECT_SQL_EXPECTED = """ - SELECT b."id", b."name", b."id_1", b."value" FROM (SELECT a."id", a."name", a."id_1", a."value" FROM (SELECT "foo"."id", "foo"."name", "fooFact"."id", "fooFact"."value" FROM "sch"."foo" INNER JOIN "sch"."fooFact" ON "foo"."id" = "fooFact"."id") a) b"""; - private static final String SELECT_INNER_JOIN_C_D = """ SELECT * FROM ((SELECT * FROM foo) c inner join fooFact on c.id = fooFact.id ) d"""; - private static final String SELECT_INNER_JOIN_C_D_EXPECTED = """ - SELECT d."id", d."name", d."id_1", d."value" FROM ((SELECT "foo"."id", "foo"."name" FROM "sch"."foo") c INNER JOIN sch.fooFact ON c.id = fooFact.id) d"""; - private static final String SELECT_INNER_JOIN_D = """ SELECT * FROM ( SELECT * FROM foo inner join fooFact on foo.id = fooFact.id ) d"""; - private static final String SELECT_INNER_JOIN_D_EXPECTED = """ - SELECT d."id", d."name", d."id_1", d."value" FROM (SELECT "foo"."id", "foo"."name", "fooFact"."id", "fooFact"."value" FROM "sch"."foo" INNER JOIN "sch"."fooFact" ON "foo"."id" = "fooFact"."id") d"""; - private static final String SELECT_INNER_JOIN = """ select * from foo inner join fooFact on foo.id = fooFact.id"""; @@ -461,6 +452,18 @@ void blankLinesInALiteralStay(@InjectService SqlGuardFactory sqlGuardFactory) th assertThat(guard.guard("select * from foo where foo.name = 'a\n\n\nb'")).contains("'a\n\n\nb'"); } + /** The expanded * of a quoted, qualified table must not split the quoted name. */ + @org.junit.jupiter.params.ParameterizedTest(name = "star over {0}") + @org.junit.jupiter.params.provider.ValueSource(strings = { "select * from \"sch\".\"foo\"", + "select * from sch.foo", "select * from \"foo\"" }) + void testQualifiedStarKeepsQuotedNamesWhole(String sql, @InjectService SqlGuardFactory sqlGuardFactory) + throws Exception { + DatabaseCatalog databaseCatalog = schemaWithTwoTableTwoCol(); + SqlGuard guard = sqlGuardFactory.create("", SCH, databaseCatalog, List.of(), dialect); + String result = guard.guard(sql); + assertThat(result).isEqualTo(SELECT_FROM_FOO_RESULT).doesNotContain("\"\""); + } + @Test void testInnerJoin(@InjectService SqlGuardFactory sqlGuardFactory) throws Exception { DatabaseCatalog databaseCatalog = schemaWithTwoTableTwoCol(); @@ -469,28 +472,43 @@ void testInnerJoin(@InjectService SqlGuardFactory sqlGuardFactory) throws Except assertThat(result).isEqualTo(SELECT_INNER_JOIN_EXPECTED); } + /** + * The derived table returns two columns named id. The resolver writes the outer + * star with a second one named id_1, a column the database does not have: the + * statement is refused, not sent broken. + */ @Test void testInnerJoin1(@InjectService SqlGuardFactory sqlGuardFactory) throws Exception { DatabaseCatalog databaseCatalog = schemaWithTwoTableTwoCol(); SqlGuard guard = sqlGuardFactory.create("", SCH, databaseCatalog, List.of(), dialect); - String result = guard.guard(SELECT_INNER_JOIN_C_D); - assertThat(result).isEqualTo(SELECT_INNER_JOIN_C_D_EXPECTED); + assertThatThrownBy(() -> guard.guard(SELECT_INNER_JOIN_C_D)).isInstanceOf(UnresolvableObjectsGuardException.class) + .hasMessageContaining("id_1"); } + /** + * The derived table returns two columns named id. The resolver writes the outer + * star with a second one named id_1, a column the database does not have: the + * statement is refused, not sent broken. + */ @Test void testInnerJoin2(@InjectService SqlGuardFactory sqlGuardFactory) throws Exception { DatabaseCatalog databaseCatalog = schemaWithTwoTableTwoCol(); SqlGuard guard = sqlGuardFactory.create("", SCH, databaseCatalog, List.of(), dialect); - String result = guard.guard(SELECT_INNER_JOIN_D); - assertThat(result).isEqualTo(SELECT_INNER_JOIN_D_EXPECTED); + assertThatThrownBy(() -> guard.guard(SELECT_INNER_JOIN_D)).isInstanceOf(UnresolvableObjectsGuardException.class) + .hasMessageContaining("id_1"); } + /** + * The derived table returns two columns named id. The resolver writes the outer + * star with a second one named id_1, a column the database does not have: the + * statement is refused, not sent broken. + */ @Test void testTripleSelect(@InjectService SqlGuardFactory sqlGuardFactory) throws Exception { DatabaseCatalog databaseCatalog = schemaWithTwoTableTwoCol(); SqlGuard guard = sqlGuardFactory.create("", SCH, databaseCatalog, List.of(), dialect); - String result = guard.guard(TRIPLE_SELECT_SQL); - assertThat(result).isEqualTo(TRIPLE_SELECT_SQL_EXPECTED); + assertThatThrownBy(() -> guard.guard(TRIPLE_SELECT_SQL)).isInstanceOf(UnresolvableObjectsGuardException.class) + .hasMessageContaining("id_1"); } @Test @@ -602,7 +620,8 @@ void testAggregationHavingWrongColumn(String agg, @InjectService SqlGuardFactory @Test void testFunctions(@InjectService SqlGuardFactory sqlGuardFactory) throws Exception { DatabaseCatalog databaseCatalog = schemaWithOneTable2Col(); - SqlGuard guard = sqlGuardFactory.create("", SCH, databaseCatalog, List.of(), dialect); + // TRIM is a function: the whitelist names it + SqlGuard guard = sqlGuardFactory.create("", SCH, databaseCatalog, List.of("trim"), dialect); String result = guard.guard(SQL_WITH_FUNCTION); assertThat(result).isEqualTo(SQL_WITH_FUNCTION_EXPECTED); assertThatThrownBy(() -> guard.guard(SQL_WITH_FUNCTION_WRONG_TABLE)).isInstanceOf(UnresolvableObjectsGuardException.class); @@ -776,6 +795,36 @@ void testFunctionBlockedWrongPatternsHaving(String fun, @InjectService SqlGuardF .isInstanceOf(GuardException.class); } + @ParameterizedTest(name = "unquoted {0} matches the lower-case whitelist") + @org.junit.jupiter.params.provider.ValueSource(strings = { "sum", "SUM", "Sum", "sUm" }) + void testUnquotedFunctionMatchesCaseInsensitively(String fun, @InjectService SqlGuardFactory sqlGuardFactory) + throws Exception { + DatabaseCatalog databaseCatalog = schemaWithOneTable2Col(); + SqlGuard guard = sqlGuardFactory.create("", SCH, databaseCatalog, AGGREGATIONS, dialect); + String result = guard.guard(String.format(SQL_WITH_ALLOWED_FUNCTION, fun)); + assertThat(result).isEqualToIgnoringCase(String.format(SQL_WITH_ALLOWED_FUNCTION_EXPECTED, "sum")); + } + + @ParameterizedTest(name = "quoted {0} does not match the whitelist entry sum") + @org.junit.jupiter.params.provider.ValueSource(strings = { "\"SUM\"", "\"Sum\"", "\"sum\"" }) + void testQuotedFunctionStaysExact(String fun, @InjectService SqlGuardFactory sqlGuardFactory) + throws Exception { + DatabaseCatalog databaseCatalog = schemaWithOneTable2Col(); + SqlGuard guard = sqlGuardFactory.create("", SCH, databaseCatalog, AGGREGATIONS, dialect); + assertThatThrownBy(() -> guard.guard(String.format(SQL_WITH_ALLOWED_FUNCTION, fun))) + .isInstanceOf(GuardException.class).hasMessage("Query has disallowed functions."); + } + + @ParameterizedTest(name = "case-insensitivity does not widen the whitelist: {0} blocked") + @org.junit.jupiter.params.provider.ValueSource(strings = { "SUMX", "PG_SLEEP", "Summary" }) + void testCaseInsensitiveMatchStaysAnchored(String fun, @InjectService SqlGuardFactory sqlGuardFactory) + throws Exception { + DatabaseCatalog databaseCatalog = schemaWithOneTable2Col(); + SqlGuard guard = sqlGuardFactory.create("", SCH, databaseCatalog, AGGREGATIONS, dialect); + assertThatThrownBy(() -> guard.guard(String.format(SQL_WITH_ALLOWED_FUNCTION, fun))) + .isInstanceOf(GuardException.class); + } + @ParameterizedTest(name = "not-allowed function {0} blocked in SELECT") @MethodSource("notAllowedFunctions") void testNotAllowedFunctionBlockedSelect(String fun, @InjectService SqlGuardFactory sqlGuardFactory) @@ -1621,4 +1670,409 @@ private static void assertNotNull(Object obj) { } } + /** + * Whatever spelling a query uses, the guard writes every object the way the + * database names it (here all lower case), quoted by the dialect. + */ + /** + * The resolver library does not look at every clause. The guard checks every table + * and column itself, so nothing outside the catalog is reached through a clause the + * library passes over, nor through a CTE or derived table that takes a catalog + * table's name. + */ + @Nested + @DisplayName("Clauses the resolver does not check") + class ClausesTheResolverDoesNotCheck { + + @ParameterizedTest(name = "{0}") + @ValueSource(strings = { "select id from foo limit (select x from secret)", + "select id from foo limit 1 offset (select x from secret)", + "select id from foo offset (select x from secret) rows", + "select id from foo fetch first (select x from secret) rows only", + "select id from foo qualify (select x from secret) = 1", + "select id, rank() over w from foo window w as (order by (select x from secret))", + "select distinct on ((select x from secret)) id from foo", + "select id from foo union select id from fooFact order by (select x from secret)", + "select id from foo union select id from fooFact limit (select x from secret)", + "select id from foo union select id from fooFact order by secret_col", + "select id from foo limit (select hidden from fooFact)", + "select id from foo limit (select 1 from secret where pw > 'm')", + "select id from foo union table secret", + "select id from foo where exists (select * from secret)" }) + void testAnUnknownTableOrColumnIsRefusedInEveryClause(String sql, + @InjectService SqlGuardFactory sqlGuardFactory) { + SqlGuard guard = sqlGuardFactory.create("", SCH, schemaWithTwoTableTwoCol(), List.of("rank"), dialect); + assertThatThrownBy(() -> guard.guard(sql)).isInstanceOf(GuardException.class); + } + + /** + * A CTE or derived table named like a catalog table does not lend its columns to + * the catalog table: {@code sch.foo} is the table, whose columns the catalog names. + */ + @ParameterizedTest(name = "{0}") + @ValueSource(strings = { "with foo as (select value as hidden from fooFact) select hidden from sch.foo", + "with foo as (select value as hidden from fooFact) select foo.hidden from sch.foo", + "with foo as (select value as hidden from fooFact) select sch.foo.hidden from sch.foo", + "select x.hidden from (select value as hidden from fooFact) foo, sch.foo x", + "select id from foo where exists (select 1 from fooFact where hidden = 1)" }) + void testAShadowDoesNotLendItsColumns(String sql, @InjectService SqlGuardFactory sqlGuardFactory) { + SqlGuard guard = sqlGuardFactory.create("", SCH, schemaWithTwoTableTwoCol(), List.of(), dialect); + assertThatThrownBy(() -> guard.guard(sql)).isInstanceOf(UnresolvableObjectsGuardException.class); + } + + /** + * An unqualified column of an enclosing SELECT is written with that SELECT's table: + * left bare, the database would take an inner table's column of the same name, + * which the catalog may not show. (In WHERE the resolver library refuses such a + * column already; in DISTINCT ON it does not look.) + */ + @Test + void testAnOuterColumnIsWrittenWithItsTable(@InjectService SqlGuardFactory sqlGuardFactory) throws Exception { + SqlGuard guard = sqlGuardFactory.create("", SCH, schemaWithTwoTableTwoCol(), List.of(), dialect); + assertThat(guard.guard( + "select distinct on ((select fooFact.value from fooFact where fooFact.id = name)) id from foo")) + .isEqualTo("SELECT DISTINCT ON ((SELECT \"fooFact\".\"value\" FROM \"sch\".\"fooFact\"" + + " WHERE \"fooFact\".\"id\" = \"sch\".\"foo\".\"name\")) \"id\" FROM \"sch\".\"foo\""); + assertThat(guard.guard( + "select distinct on ((select fooFact.value from fooFact where fooFact.id = name)) f.id from foo f")) + .isEqualTo("SELECT DISTINCT ON ((SELECT \"fooFact\".\"value\" FROM \"sch\".\"fooFact\"" + + " WHERE \"fooFact\".\"id\" = f.\"name\")) f.\"id\" FROM \"sch\".\"foo\" AS f"); + // an inner table of the same name would take the qualifier: refused + assertThatThrownBy(() -> guard.guard( + "select distinct on ((select f.value from fooFact f where f.id = name)) f.id from foo f")) + .isInstanceOf(UnresolvableObjectsGuardException.class); + } + + /** + * A part of the statement no walk of the guard covers (here a PIVOT) carries + * columns no check has seen: the last net, which reads every field of the parsed + * statement, refuses it. + */ + @Test + void testAPartNoWalkCoversIsRefused(@InjectService SqlGuardFactory sqlGuardFactory) { + SqlGuard guard = sqlGuardFactory.create("", SCH, schemaWithTwoTableTwoCol(), List.of("count"), dialect); + assertThatThrownBy(() -> guard.guard("select * from foo pivot (count(id) for name in (1, 2))")) + .isInstanceOf(GuardException.class); + } + + static Stream checkedClauses() { + return Stream.of( + org.junit.jupiter.params.provider.Arguments.of("select id from foo limit 10", + "SELECT \"id\" FROM \"sch\".\"foo\" LIMIT 10"), + org.junit.jupiter.params.provider.Arguments.of("select id from foo limit 10 offset 5", + "SELECT \"id\" FROM \"sch\".\"foo\" LIMIT 10 OFFSET 5"), + org.junit.jupiter.params.provider.Arguments.of("select id from foo order by id fetch first 3 rows only", + "SELECT \"id\" FROM \"sch\".\"foo\" ORDER BY \"id\" FETCH FIRST 3 ROWS ONLY"), + org.junit.jupiter.params.provider.Arguments.of("select id as k from foo order by k", + "SELECT \"id\" AS k FROM \"sch\".\"foo\" ORDER BY \"K\""), + org.junit.jupiter.params.provider.Arguments.of("select id from foo union select id from fooFact order by id", + "SELECT \"id\" FROM \"sch\".\"foo\" UNION SELECT \"id\" FROM \"sch\".\"fooFact\" ORDER BY \"id\""), + org.junit.jupiter.params.provider.Arguments.of("select id from foo union select id from fooFact order by 1 limit 2", + "SELECT \"id\" FROM \"sch\".\"foo\" UNION SELECT \"id\" FROM \"sch\".\"fooFact\" ORDER BY 1 LIMIT 2"), + org.junit.jupiter.params.provider.Arguments.of("select name, rank() over (partition by name order by id) from foo", + "SELECT \"name\", rank() OVER (PARTITION BY \"name\" ORDER BY \"id\") FROM \"sch\".\"foo\""), + org.junit.jupiter.params.provider.Arguments.of("select id, rank() over w from foo window w as (order by name)", + // the window is written where it is used, its names quoted + "SELECT \"id\", rank() OVER (ORDER BY \"name\") FROM \"sch\".\"foo\""), + org.junit.jupiter.params.provider.Arguments.of("select distinct on (name) name, id from foo order by name, id", + "SELECT DISTINCT ON (\"name\") \"name\", \"id\" FROM \"sch\".\"foo\" ORDER BY \"name\", \"id\""), + org.junit.jupiter.params.provider.Arguments.of("select id from foo where exists (select 1 from fooFact where fooFact.id = foo.id)", + "SELECT \"id\" FROM \"sch\".\"foo\" WHERE EXISTS (SELECT 1 FROM \"sch\".\"fooFact\" WHERE \"fooFact\".\"id\" = \"foo\".\"id\")"), + org.junit.jupiter.params.provider.Arguments.of("select id from foo where exists (select * from fooFact where fooFact.id = foo.id)", + "SELECT \"id\" FROM \"sch\".\"foo\" WHERE EXISTS (SELECT \"fooFact\".\"id\", \"fooFact\".\"value\" FROM \"sch\".\"fooFact\" WHERE \"fooFact\".\"id\" = \"foo\".\"id\")"), + org.junit.jupiter.params.provider.Arguments.of("with c as (select id from fooFact) select foo.name from foo join c on c.id = foo.id", + "WITH c AS (SELECT \"id\" FROM \"sch\".\"fooFact\") SELECT \"foo\".\"name\" FROM \"sch\".\"foo\" JOIN \"C\" ON \"C\".\"id\" = \"foo\".\"id\""), + org.junit.jupiter.params.provider.Arguments.of("select t.v from (select value as v from fooFact) t limit 1", + "SELECT t.\"V\" FROM (SELECT \"value\" AS v FROM \"sch\".\"fooFact\") t LIMIT 1")); + } + + @ParameterizedTest(name = "{0}") + @MethodSource("checkedClauses") + void testWhatTheCatalogHoldsStillPasses(String sql, String expected, + @InjectService SqlGuardFactory sqlGuardFactory) throws Exception { + SqlGuard guard = sqlGuardFactory.create("", SCH, schemaWithTwoTableTwoCol(), List.of("rank"), dialect); + assertThat(guard.guard(sql)).isEqualTo(expected); + } + } + + @Nested + @DisplayName("Canonical Name Tests") + class CanonicalNameTests { + + @org.junit.jupiter.params.ParameterizedTest(name = "{0} resolves to the database spelling") + @org.junit.jupiter.params.provider.ValueSource(strings = { "SELECT * FROM SCH.FOO", "select * from Foo", + "select * from \"sch\".\"foo\"", "select * from SCH.\"foo\"", "select * from \"sch\".foo", + "select * from `sch`.`foo`" }) + void testAnySpellingResolvesToTheDatabaseName(String sql, @InjectService SqlGuardFactory sqlGuardFactory) + throws Exception { + SqlGuard guard = sqlGuardFactory.create("", SCH, schemaWithTwoTableTwoCol(), List.of(), dialect); + assertThat(guard.guard(sql)).isEqualTo(SELECT_FROM_FOO_RESULT); + } + + @Test + void testExplicitColumnsAndConditionsResolve(@InjectService SqlGuardFactory sqlGuardFactory) throws Exception { + SqlGuard guard = sqlGuardFactory.create("", SCH, schemaWithTwoTableTwoCol(), List.of(), dialect); + String result = guard.guard("SELECT FOO.ID, NAME FROM SCH.FOO WHERE Foo.Name = 'x' ORDER BY ID"); + assertThat(result).contains("FROM \"sch\".\"foo\"").contains("\"foo\".\"id\"").contains("\"name\"") + .doesNotContain("\"FOO\"").doesNotContain("\"SCH\"").doesNotContain("\"ID\"") + .doesNotContain("\"NAME\"").doesNotContain("\"Name\""); + } + + @Test + void testAnAliasKeepsItsSpellingAndItsColumnsResolve(@InjectService SqlGuardFactory sqlGuardFactory) + throws Exception { + SqlGuard guard = sqlGuardFactory.create("", SCH, schemaWithTwoTableTwoCol(), List.of(), dialect); + String result = guard.guard("SELECT F.ID, F.NAME FROM SCH.FOO F"); + assertThat(result).contains("FROM \"sch\".\"foo\" AS F").contains("\"id\"").contains("\"name\"") + .doesNotContain("\"ID\"").doesNotContain("\"FOO\""); + } + + /** + * A quoted name picks its twin exactly; an unquoted one the twin the database + * folds it to, as H2 and Oracle (upper) or PostgreSQL (lower) do. + */ + @Test + void testTwinsDifferingOnlyByCase(@InjectService SqlGuardFactory sqlGuardFactory) throws Exception { + SqlGuard upper = sqlGuardFactory.create("", SCH, schemaWithCaseTwins(), List.of(), dialect); + assertThat(upper.guard("SELECT \"ID\" FROM \"FOO\"")).isEqualTo("SELECT \"ID\" FROM \"sch\".\"FOO\""); + assertThat(upper.guard("SELECT \"id\" FROM \"foo\"")).isEqualTo("SELECT \"id\" FROM \"sch\".\"foo\""); + assertThat(upper.guard("SELECT id FROM foo")).isEqualTo("SELECT \"ID\" FROM \"sch\".\"FOO\""); + assertThat(upper.guard("SELECT id FROM Foo")).isEqualTo("SELECT \"ID\" FROM \"sch\".\"FOO\""); + + SqlGuard lower = sqlGuardFactory.create("", SCH, schemaWithCaseTwins(), List.of(), + folding(org.eclipse.daanse.sql.dialect.api.IdentifierCaseFolding.LOWER)); + assertThat(lower.guard("SELECT ID FROM FOO")).isEqualTo("SELECT \"id\" FROM \"sch\".\"foo\""); + assertThat(lower.guard("SELECT ID FROM Foo")).isEqualTo("SELECT \"id\" FROM \"sch\".\"foo\""); + assertThat(lower.guard("SELECT \"ID\" FROM \"FOO\"")).isEqualTo("SELECT \"ID\" FROM \"sch\".\"FOO\""); + } + + /** A database that keeps names as written: a spelling that is neither twin is ambiguous. */ + @Test + void testTwinsWithoutFoldingAreAmbiguous(@InjectService SqlGuardFactory sqlGuardFactory) throws Exception { + SqlGuard guard = sqlGuardFactory.create("", SCH, schemaWithCaseTwins(), List.of(), + folding(org.eclipse.daanse.sql.dialect.api.IdentifierCaseFolding.PRESERVE)); + assertThat(guard.guard("SELECT id FROM foo")).isEqualTo("SELECT \"id\" FROM \"sch\".\"foo\""); + assertThat(guard.guard("SELECT ID FROM FOO")).isEqualTo("SELECT \"ID\" FROM \"sch\".\"FOO\""); + assertThatThrownBy(() -> guard.guard("SELECT id FROM Foo")) + .isInstanceOf(UnresolvableObjectsGuardException.class).hasMessageContaining("ambiguous"); + } + + /** + * Whoever quotes a name means exactly that name: a quoted schema, table, column, + * qualifier or CTE reference that the catalog has only in another case is refused, + * as Oracle, H2, Derby and PostgreSQL refuse it. + */ + @ParameterizedTest(name = "{0}") + @ValueSource(strings = { "select * from \"foo\"", "select * from \"Foo\"", "select \"id\" from foo", + "select foo.\"Id\" from foo", "select * from \"sch\".foo", "select \"foo\".id from foo", + "select `foo`.`id` from `foo`", "with c as (select id from foo) select * from \"c\"", + "select t.\"k\" from (select id as k from foo) t" }) + void testAQuotedNameMustMatchExactly(String sql, @InjectService SqlGuardFactory sqlGuardFactory) { + SqlGuard guard = sqlGuardFactory.create("", "SCH", upperCaseCatalog(), List.of(), dialect); + assertThatThrownBy(() -> guard.guard(sql)).isInstanceOf(UnresolvableObjectsGuardException.class); + } + + static Stream quotedExactly() { + return Stream.of( + org.junit.jupiter.params.provider.Arguments.of("select * from \"FOO\"", + "SELECT \"FOO\".\"ID\", \"FOO\".\"NAME\" FROM \"SCH\".\"FOO\""), + org.junit.jupiter.params.provider.Arguments.of("select \"ID\" from \"SCH\".foo", + "SELECT \"ID\" FROM \"SCH\".\"FOO\""), + org.junit.jupiter.params.provider.Arguments.of("select \"FOO\".id from foo", + "SELECT \"FOO\".\"ID\" FROM \"SCH\".\"FOO\""), + org.junit.jupiter.params.provider.Arguments.of("select `FOO`.`ID` from `FOO`", + "SELECT \"FOO\".\"ID\" FROM \"SCH\".\"FOO\""), + org.junit.jupiter.params.provider.Arguments.of("select \"Mixed\".\"Id\" from \"Mixed\"", + "SELECT \"Mixed\".\"Id\" FROM \"SCH\".\"Mixed\""), + org.junit.jupiter.params.provider.Arguments.of("with c as (select id from foo) select * from \"C\"", + "WITH c AS (SELECT \"ID\" FROM \"SCH\".\"FOO\") SELECT \"C\".\"ID\" FROM \"C\""), + org.junit.jupiter.params.provider.Arguments.of("select t.\"K\" from (select id as k from foo) t", + "SELECT t.\"K\" FROM (SELECT \"ID\" AS k FROM \"SCH\".\"FOO\") t")); + } + + @ParameterizedTest(name = "{0}") + @MethodSource("quotedExactly") + void testAQuotedNameThatMatchesExactlyPasses(String sql, String expected, + @InjectService SqlGuardFactory sqlGuardFactory) throws Exception { + SqlGuard guard = sqlGuardFactory.create("", "SCH", upperCaseCatalog(), List.of(), dialect); + assertThat(guard.guard(sql)).isEqualTo(expected); + } + + /** + * A quoted ORDER BY entry names an output alias only by the alias's exact name. An + * entry that is not the alias is checked as a column, so it cannot reach a column + * the catalog does not hold. + */ + @Test + void testAQuotedOrderByNamesAnAliasExactly(@InjectService SqlGuardFactory sqlGuardFactory) throws Exception { + SqlGuard upper = sqlGuardFactory.create("", "SCH", upperCaseCatalog(), List.of(), dialect); + assertThat(upper.guard("select foo_id as k from fact order by \"K\"")) + .isEqualTo("SELECT \"FOO_ID\" AS k FROM \"SCH\".\"FACT\" ORDER BY \"K\""); + assertThatThrownBy(() -> upper.guard("select foo_id as k from fact order by \"k\"")) + .isInstanceOf(UnresolvableObjectsGuardException.class); + + SqlGuard lower = sqlGuardFactory.create("", SCH, schemaWithTwoTableTwoCol(), List.of(), + folding(org.eclipse.daanse.sql.dialect.api.IdentifierCaseFolding.LOWER)); + assertThat(lower.guard("select id as salary from foo order by \"salary\"")) + .isEqualTo("SELECT \"id\" AS salary FROM \"sch\".\"foo\" ORDER BY \"salary\""); + assertThatThrownBy(() -> lower.guard("select id as salary from foo order by \"SALARY\"")) + .isInstanceOf(UnresolvableObjectsGuardException.class); + } + + private Dialect folding(org.eclipse.daanse.sql.dialect.api.IdentifierCaseFolding folding) { + return new H2Dialect() { + @Override + public org.eclipse.daanse.sql.dialect.api.IdentifierCaseFolding caseFolding() { + return folding; + } + }; + } + + @Test + void testUnknownNamesStayUnknown(@InjectService SqlGuardFactory sqlGuardFactory) throws Exception { + SqlGuard guard = sqlGuardFactory.create("", SCH, schemaWithTwoTableTwoCol(), List.of(), dialect); + assertThatThrownBy(() -> guard.guard("SELECT * FROM BAR")).isInstanceOf(UnresolvableObjectsGuardException.class); + assertThatThrownBy(() -> guard.guard("SELECT FOO.NOPE FROM FOO")) + .isInstanceOf(UnresolvableObjectsGuardException.class); + } + + /** + * A database that folds unquoted names to upper case (H2, Oracle): every object is + * written with its catalog spelling, in subqueries, set operations, derived tables + * and CTEs too. Each expected statement was run on H2. + */ + static Stream upperCaseDatabase() { + return Stream.of( + org.junit.jupiter.params.provider.Arguments.of("select * from foo", + "SELECT \"FOO\".\"ID\", \"FOO\".\"NAME\" FROM \"SCH\".\"FOO\""), + org.junit.jupiter.params.provider.Arguments.of("select f.id from foo f", + "SELECT f.\"ID\" FROM \"SCH\".\"FOO\" AS f"), + org.junit.jupiter.params.provider.Arguments.of("select sum(val) as val from fact group by foo_id order by val", + "SELECT sum(\"VAL\") AS val FROM \"SCH\".\"FACT\" GROUP BY \"FOO_ID\" ORDER BY \"VAL\""), + org.junit.jupiter.params.provider.Arguments.of("select * from foo join fact using (id)", + "SELECT \"FOO\".\"ID\", \"FOO\".\"NAME\", \"FACT\".\"ID\", \"FACT\".\"FOO_ID\", \"FACT\".\"VAL\" FROM \"SCH\".\"FOO\" JOIN \"SCH\".\"FACT\" USING (\"ID\")"), + org.junit.jupiter.params.provider.Arguments.of("select id from foo union select id from fact", + "SELECT \"ID\" FROM \"SCH\".\"FOO\" UNION SELECT \"ID\" FROM \"SCH\".\"FACT\""), + org.junit.jupiter.params.provider.Arguments.of("select name from foo where exists (select 1 from fact where fact.foo_id = foo.id)", + "SELECT \"NAME\" FROM \"SCH\".\"FOO\" WHERE EXISTS (SELECT 1 FROM \"SCH\".\"FACT\" WHERE \"FACT\".\"FOO_ID\" = \"FOO\".\"ID\")"), + org.junit.jupiter.params.provider.Arguments.of("select t.name from (select id, name from foo) t", + "SELECT t.\"NAME\" FROM (SELECT \"ID\", \"NAME\" FROM \"SCH\".\"FOO\") t"), + org.junit.jupiter.params.provider.Arguments.of("select t.k from (select id as k from foo) t", + "SELECT t.\"K\" FROM (SELECT \"ID\" AS k FROM \"SCH\".\"FOO\") t"), + org.junit.jupiter.params.provider.Arguments.of("select t.k from (select id as \"k\" from foo) t", + "SELECT t.\"k\" FROM (SELECT \"ID\" AS \"k\" FROM \"SCH\".\"FOO\") t"), + org.junit.jupiter.params.provider.Arguments.of("select a.id from foo a where a.id in (select a.foo_id from fact a)", + "SELECT a.\"ID\" FROM \"SCH\".\"FOO\" AS a WHERE a.\"ID\" IN (SELECT a.\"FOO_ID\" FROM \"SCH\".\"FACT\" AS a)"), + org.junit.jupiter.params.provider.Arguments.of("with c as (select id, name from foo) select name from c", + "WITH c AS (SELECT \"ID\", \"NAME\" FROM \"SCH\".\"FOO\") SELECT \"NAME\" FROM \"C\""), + org.junit.jupiter.params.provider.Arguments.of("with foo as (select foo_id as id from fact) select foo.id from foo", + "WITH foo AS (SELECT \"FOO_ID\" AS id FROM \"SCH\".\"FACT\") SELECT \"FOO\".\"ID\" FROM \"FOO\""), + org.junit.jupiter.params.provider.Arguments.of("select o.extra from other.foo o join sch.foo s on o.id = s.id", + "SELECT o.\"EXTRA\" FROM \"OTHER\".\"FOO\" AS o JOIN \"SCH\".\"FOO\" AS s ON o.\"ID\" = s.\"ID\""), + org.junit.jupiter.params.provider.Arguments.of("select mixed.id, MIXED.VAL from mixed", + "SELECT \"Mixed\".\"Id\", \"Mixed\".\"Val\" FROM \"SCH\".\"Mixed\""), + org.junit.jupiter.params.provider.Arguments.of( + "select foo_id as k, sum(val) as total from fact group by foo_id order by total desc, k", + "SELECT \"FOO_ID\" AS k, sum(\"VAL\") AS total FROM \"SCH\".\"FACT\" GROUP BY \"FOO_ID\" ORDER BY \"TOTAL\" DESC, \"K\""), + org.junit.jupiter.params.provider.Arguments.of( + "select t.k from (select id as k from foo order by k) t", + "SELECT t.\"K\" FROM (SELECT \"ID\" AS k FROM \"SCH\".\"FOO\" ORDER BY \"K\") t"), + org.junit.jupiter.params.provider.Arguments.of( + "select name as id from foo order by id, name", + "SELECT \"NAME\" AS id FROM \"SCH\".\"FOO\" ORDER BY \"ID\", \"NAME\""), + org.junit.jupiter.params.provider.Arguments.of("select `FOO`.id from FOO", + "SELECT \"FOO\".\"ID\" FROM \"SCH\".\"FOO\"")); + } + + @ParameterizedTest(name = "{0}") + @MethodSource("upperCaseDatabase") + void testEveryScopeResolvesToTheDatabaseName(String sql, String expected, + @InjectService SqlGuardFactory sqlGuardFactory) throws Exception { + SqlGuard guard = sqlGuardFactory.create("", "SCH", upperCaseCatalog(), List.of("sum"), dialect); + assertThat(guard.guard(sql)).isEqualTo(expected); + } + + @Test + void testACteReferenceTakesTheDialectsFolding(@InjectService SqlGuardFactory sqlGuardFactory) + throws Exception { + Dialect lowerFolding = new H2Dialect() { + @Override + public org.eclipse.daanse.sql.dialect.api.IdentifierCaseFolding caseFolding() { + return org.eclipse.daanse.sql.dialect.api.IdentifierCaseFolding.LOWER; + } + }; + SqlGuard guard = sqlGuardFactory.create("", SCH, schemaWithTwoTableTwoCol(), List.of(), lowerFolding); + assertThat(guard.guard("WITH C AS (SELECT ID FROM FOO) SELECT C.ID FROM C")) + .isEqualTo("WITH C AS (SELECT \"id\" FROM \"sch\".\"foo\") SELECT \"c\".\"id\" FROM \"c\""); + } + + @Test + void testOrderByAnAliasDoesNotBypassTheChecks(@InjectService SqlGuardFactory sqlGuardFactory) + throws Exception { + SqlGuard guard = sqlGuardFactory.create("", "SCH", upperCaseCatalog(), List.of("sum"), dialect); + assertThatThrownBy(() -> guard.guard("select id as k from foo order by nope")) + .isInstanceOf(UnresolvableObjectsGuardException.class); + assertThatThrownBy(() -> guard.guard("select id as k from foo order by pg_sleep(1)")) + .isInstanceOf(GuardException.class).hasMessageContaining("disallowed functions"); + assertThatThrownBy(() -> guard.guard("select id as k from foo order by k, (select extra from other.fact)")) + .isInstanceOf(UnresolvableObjectsGuardException.class); + assertThatThrownBy(() -> guard.guard("select id as k from foo order by t.k")) + .isInstanceOf(GuardException.class); + } + + private DatabaseCatalog upperCaseCatalog() { + DatabaseTable foo = table("FOO", "ID", "NAME"); + DatabaseTable fact = table("FACT", "ID", "FOO_ID", "VAL"); + DatabaseTable mixed = table("Mixed", "Id", "Val"); + DatabaseTable otherFoo = table("FOO", "ID", "EXTRA"); + DatabaseSchema sch = schema("SCH", foo, fact, mixed); + DatabaseSchema other = schema("OTHER", otherFoo); + List schemas = List.of(sch, other); + DatabaseCatalog catalog = mock(DatabaseCatalog.class); + when(catalog.getName()).thenReturn(null); + when(catalog.getDatabaseSchemas()).thenReturn(schemas); + return catalog; + } + + private DatabaseTable table(String name, String... columnNames) { + List columns = new java.util.ArrayList<>(); + for (String columnName : columnNames) { + DatabaseColumn column = mock(DatabaseColumn.class); + when(column.getName()).thenReturn(columnName); + columns.add(column); + } + DatabaseTable table = mock(DatabaseTable.class); + when(table.getName()).thenReturn(name); + when(table.getDatabaseColumns()).thenReturn(columns); + return table; + } + + private DatabaseSchema schema(String name, DatabaseTable... tables) { + List list = List.of(tables); + DatabaseSchema schema = mock(DatabaseSchema.class); + when(schema.getName()).thenReturn(name); + when(schema.getDatabaseTables()).thenReturn(list); + return schema; + } + + private DatabaseCatalog schemaWithCaseTwins() { + DatabaseColumn lowerId = mock(DatabaseColumn.class); + when(lowerId.getName()).thenReturn("id"); + DatabaseTable lower = mock(DatabaseTable.class); + when(lower.getName()).thenReturn("foo"); + when(lower.getDatabaseColumns()).thenReturn(List.of(lowerId)); + DatabaseColumn upperId = mock(DatabaseColumn.class); + when(upperId.getName()).thenReturn("ID"); + DatabaseTable upper = mock(DatabaseTable.class); + when(upper.getName()).thenReturn("FOO"); + when(upper.getDatabaseColumns()).thenReturn(List.of(upperId)); + DatabaseSchema schema = mock(DatabaseSchema.class); + when(schema.getName()).thenReturn(SCH); + when(schema.getDatabaseTables()).thenReturn(List.of(lower, upper)); + DatabaseCatalog catalog = mock(DatabaseCatalog.class); + when(catalog.getName()).thenReturn(null); + when(catalog.getDatabaseSchemas()).thenReturn(List.of(schema)); + return catalog; + } + } }