diff --git a/src/sqlancer/voltdb/README.md b/src/sqlancer/voltdb/README.md index c01107aa0..690e2e158 100644 --- a/src/sqlancer/voltdb/README.md +++ b/src/sqlancer/voltdb/README.md @@ -4,8 +4,8 @@ A SQLancer provider for [VoltDB](https://www.voltactivedata.com/), developed for VoltDB schemas, both replicated and partitioned tables, fills them with single-row inserts, and runs SQLancer's oracles against them through the VoltDB JDBC driver. -**Status: milestone 1.** The provider creates schemas and data. Its only oracle, `SMOKE`, reads every table and checks -nothing but that the queries succeed. The logic-bug oracles come next: NoREC (milestone 2), then TLP WHERE +**Status: milestone 2.** The provider creates schemas and data and runs the NoREC logic-bug oracle (the default). +`SMOKE`, from milestone 1, only reads every table and checks that the queries succeed. TLP WHERE comes next (milestone 3). ## Versions @@ -51,10 +51,10 @@ holds data you care about: DDL from SQLancer serializes with all other DDL on th ```bash java -jar target/sqlancer-*.jar \ - --num-threads 4 --num-tries 4 --timeout-seconds 1800 --num-queries 5 \ + --num-threads 4 --num-tries 4 --timeout-seconds 1800 --num-queries 100 \ --random-seed 20261102 --username "" --password "" \ --host localhost --port 21212 --database-prefix db \ - voltdb --oracle SMOKE + voltdb --oracle NOREC ``` SQLancer's options come before `voltdb`, the provider's after it. @@ -63,15 +63,16 @@ SQLancer's options come before `voltdb`, the provider's after it. | --- | --- | | `--num-threads`, `--num-tries` | Threads that run at once, and how many run in total. Use the same number for both. Every thread is one SQLancer "database". VoltDB runs one DDL statement at a time, so more than about 4 threads mostly wait. | | `--timeout-seconds` | How long the run lasts. | -| `--num-queries` | Oracle checks per database before a thread drops it and generates a new one. With `SMOKE`, keep it small so schemas keep changing. | +| `--num-queries` | Oracle checks per database before a thread drops it and generates a new one. 100 suits NoREC; with `SMOKE`, keep it small so schemas keep changing. | | `--random-seed` | Thread *n* uses seed + *n*. A seed and the same server state give the same statements, but thread timing is not deterministic. | | `--username`, `--password` | Empty for a server without security (SQLancer's default is `sqlancer`). | | `--host`, `--port` | A server's client port. Defaults: localhost, 21212. | | `--database-prefix` | Prefix of each thread's table names. Default `database`; `db` keeps the logs short. | -| `--oracle` | `SMOKE` (the default, and the only oracle so far). | +| `--oracle` | `NOREC` (the default) or `SMOKE`. | | `--max-num-tables` | Tables per database, 1 to this (default 3). | | `--max-num-indexes` | CREATE INDEX statements per database, 0 to this (default 4). | | `--retry-seconds` | How long a statement rejected because of another thread's schema change is retried (default 120). | +| `--avoid-known-bugs` | `true` (the default) keeps the generator away from the VoltDB bugs listed below, so a failure is something new. `false` generates them too. | ## Reading the results @@ -96,6 +97,40 @@ Logs are in `logs/voltdb/` under the directory you run from: The exit code is 0 when no thread failed. To reproduce a failure, start from an empty server and run the statements in `.log` in order (with `sqlcmd`, for example). +A NoREC failure ends with the two queries, `-- optimized:` and `-- unoptimized:`, and either the two counts that differ +("the row counts of the following queries mismatch") or the unexpected error. + +## The NoREC oracle + +NoREC ([Rigger and Su, 2020](https://doi.org/10.1145/3368089.3409704)) runs one random predicate two ways and compares +the counts: + +```sql +-- optimized: the predicate is a WHERE clause, which the planner can push into index scans, joins and partitions +SELECT COUNT(*) FROM t0, t1 LEFT JOIN t2 ON ... WHERE p; +-- unoptimized: the predicate is evaluated on every row, so the planner cannot use it +SELECT COALESCE(SUM(c), 0) FROM (SELECT CASE WHEN p THEN 1 ELSE 0 END AS c FROM t0, t1 LEFT JOIN t2 ON ...) AS res; +``` + +Half the time the optimized query selects the rows instead of counting them, and the oracle counts the result set. + +The VoltDB expression generator (`gen/VoltDBExpressionGenerator`) builds predicates from columns and constants with +AND, OR, NOT, the comparisons, BETWEEN, IN, LIKE, IS [NOT] NULL, `+ - * /`, `||` and ABS. To stay inside what VoltDB +supports: + +- **Joins follow partitioning.** Partitioned tables are joined to the first partitioned table (the anchor) on their + partitioning columns, so every query runs in one partition or as a correct multi-partition join. The ON condition is + the equality alone: VoltDB plans the join only when it can see that equality, and an added condition that folds to + FALSE, such as `pc = pc AND (1 = 0)`, takes it away ("This query is not plannable"). A partitioned table whose + partitioning column cannot be compared with the anchor's is left out. Replicated tables are in the FROM list or, + sometimes, joined explicitly (INNER, LEFT, RIGHT or FULL; RIGHT only when `--avoid-known-bugs` is false) with a random + ON condition. +- **Typed NULLs.** A NULL constant is `CAST(NULL AS type)`; VoltDB rejects a bare NULL whose type it cannot infer. +- **Syntax.** Negative constants are in parentheses (`- -5` is a syntax error), `MOD` is never written as `%`, and an + IN predicate is never the operand of a comparison or another IN (`x = (y IN (1))` is a syntax error). +- **Every WHERE clause references a column.** VoltDB does not support a join filter that depends on none of the joined + tables. + ## How the provider maps SQLancer onto VoltDB - **One schema, many databases.** A VoltDB cluster has a single schema, so each SQLancer database is the set of tables @@ -131,6 +166,15 @@ Each is listed in `VoltDBErrors` with its reason. The run fails on any other err | --- | --- | --- | | INSERT | `CONSTRAINT VIOLATION` | Random values repeat existing keys. | | CREATE INDEX | `is not empty` | VoltDB cannot add a UNIQUE index to a table that has rows (an ASSUMEUNIQUE index it can). | +| SELECT | `Join with filters that do not depend on joined tables is not supported` | A predicate that references a column can still fold to a constant, such as `(FALSE AND t.c) = FALSE`. | +| SELECT | `Attempted to divide`, `data exception: division by zero` | Division by zero, at run time or in constants the planner folds. | +| SELECT | `Invalid result value` | A FLOAT result is infinite or NaN. | +| SELECT | `will overflow BigInt storage`, `causing overflow/underflow`, `out of range for the destination type` | Integer, DECIMAL or cast overflow. | +| SELECT | `Numeric conversion error to type DECIMAL` | DECIMAL overflow in an expression of constants, which the planner folds. The message quotes a truncated value. | + +The two NoREC queries can evaluate an expression on different rows (the optimized query may skip rows through an index +or a join), so only one of them may hit a run-time error. The oracle treats an expected error in either query as no +result. VoltDB also drops a CREATE INDEX that duplicates an existing index, logging "Dropping index ... because it duplicates index ..." at WARN. The statement succeeds, so the provider ignores it. @@ -140,9 +184,38 @@ index ..." at WARN. The statement succeeds, so the provider ignores it. | Ticket | Issue | Workaround | | --- | --- | --- | | ENG-30489 | Closing a JDBC connection twice closes the client every other connection to the same URL shares, failing their in-flight calls. SQLancer closes each connection twice. | `VoltDBConnection.close()` is idempotent. | -| ENG-4643 | JDBC `getString` on a NULL returns the type's NULL sentinel (INTEGER, TINYINT, FLOAT) or throws (DECIMAL, BOOLEAN, DATE, TIMESTAMP). SQLancer's oracles compare results with `getString`. | Not needed yet; the NoREC and TLP oracles will need one. | +| ENG-4643 | JDBC `getString` on a NULL returns the type's NULL sentinel (INTEGER, TINYINT, FLOAT) or throws (DECIMAL, BOOLEAN, DATE, TIMESTAMP). | Not needed: NoREC reads only counts. TLP compares values and will need one. | +| ENG-12656 | An index scan for `<`, `<=`, `>`, `>=` or BETWEEN on a VARBINARY(n) column, and for `=` when the column leads a multi-column unique index, fails ("Type VARCHAR can't be cast as VARBINARY") when the value, a constant or another table's column, is longer than n bytes. Found again by NoREC. | While `--avoid-known-bugs` is true, VARBINARY values are never compared with `<`, `>`, `<=`, `>=` or BETWEEN, a VARBINARY comparison has a constant on one side, VARBINARY constants are at most one byte, and VARBINARY partitioning columns are joined only when their sizes match. | | ENG-22880 | A BIGINT literal at the type's minimum is stored as NULL instead of rejected. A FLOAT at -1.7976931348623157E308 and an INTEGER expression equal to INTEGER's minimum do the same. | Never generated. | +The bugs below were found by NoREC in milestone 2. While `--avoid-known-bugs` is true (the default) the generator +avoids each one as described; set it to false to check whether a fix works. + +| Ticket | Issue | Workaround | +| --- | --- | --- | +| ENG-30493 | BOOLEAN values order TRUE < FALSE where the EE compares them: `<`, `>`, BETWEEN and ORDER BY give wrong rows. | BOOLEAN values are only compared with `=` and `<>`. | +| ENG-30494 | BOOLEAN literals are passed to the EE as parameters of the wrong value or type: cast errors and wrong rows. | Boolean constants are written `(1 = 1)` and `(1 = 0)`. | +| ENG-30495 | A WHERE clause that folds to a constant NULL crashes the planner (NPE). | No NULL constants; NULLs come from the data. | +| ENG-30496 | LIKE inside CASE WHEN crashes the planner when its left operand is a constant or its pattern has no wildcard or is just `%`. | LIKE's left operand is a string column; the pattern has a wildcard and a literal character. | +| ENG-30497 | With an outer join, a boolean expression over the inner table, such as `(t.c IS NULL) IS NOT NULL` or `(t.c IS NULL) = TRUE`, turns the join into an inner join: wrong rows. | With an outer join, boolean operands of comparisons, IN and IS NULL are columns or constants. | +| ENG-30499 | Comparing a DATE constant with a TIMESTAMP constant crashes the planner (ClassCastException). | Temporal constants are `CAST('...' AS TIMESTAMP)`. | +| ENG-30500 | A boolean expression `IN (NULL, ...)` gives wrong rows. | IN list elements are constants that are not NULL. | +| ENG-30502 | Unary minus on a NULL integer or FLOAT gives a non-NULL value. | `0 - x` instead of `-x`. | +| ENG-30503 | IN lists ignore NULL elements: `x NOT IN (NULL, ...)` is TRUE instead of NULL. | As ENG-30500. | +| ENG-30504 | `NOT (b OR c)` over BOOLEAN values fails in the planner (cast error) when it is an operand: `NOT (NOT (b OR c))`, `(NOT (b OR c)) IS NOT NULL`. | NOT is never applied directly to OR. | +| ENG-30505 | `x IN ('...')` on a unique VARCHAR(n) or VARBINARY(n) column fails when a value is longer than n. | String and binary constants are at most one character or byte, as for ENG-30509 and ENG-12656. | +| ENG-30506 | In a parenthesized AND/OR list, an operand after an IN predicate that starts with a function call or a negative literal crashes the parser (NPE). | Function calls are always printed in parentheses, whatever `--avoid-known-bugs` is. | +| ENG-30507 | With an outer join, a WHERE IN predicate on an indexed column is applied as part of the join instead of after it, so it does not remove the rows it should: wrong rows. | No IN predicates when the query has an outer join. | +| ENG-30508 | A join filter of constants only, which VoltDB rejects ("Join with filters that do not depend on joined tables"), fails with an internal NumberFormatException instead when it is an IN with a DECIMAL constant on the left. | The internal error is an expected error, like the rejection it replaces. | +| ENG-30509 | A range scan on a multi-column index compares a VARCHAR(n) column with only the first n characters of a longer value, a constant or another table's column: `c >= '-2'` matches `'-'`, and so does `c LIKE '-2%'`. Wrong rows. | Strings are never compared with `<`, `>`, `<=`, `>=` or BETWEEN; string constants and a LIKE pattern's literal prefix are at most one character (the smallest VARCHAR). | +| ENG-30510 | After turning a RIGHT JOIN into a LEFT JOIN, VoltDB can use an ON condition on the preserved table as that table's index range, dropping rows that should be null-extended. Wrong rows. | No RIGHT JOIN (a LEFT JOIN with the tables swapped is the same). | +| ENG-30511 | An index nested-loop join's range scan on a narrower integer column, with a key from a wider column that is below the narrower type's range, matches every row: `b > s` is true for BIGINT `b = -40000` and SMALLINT `s = 5`. Wrong rows. | Ordered comparisons of numbers have a constant on one side, and BETWEEN on numbers has constant bounds. | +| ENG-30512 | COUNT(*) over an empty index range, such as `x BETWEEN 9 AND 1`, is negative (INDEX COUNT). | BETWEEN bounds are constants in ascending order. | +| ENG-30513 | Comparing a FLOAT with a DECIMAL of magnitude 2^63 or more gives wrong results; the DECIMAL appears to wrap through a 64-bit integer. Such DECIMALs come from the data and from arithmetic. | A numeric comparison, BETWEEN or IN uses only FLOAT operands or only exact ones (integers and DECIMAL). | +| ENG-30514 | A primary key column that is not declared NOT NULL accepts NULL, but the planner assumes it is never NULL: `LEFT JOIN t ON ... WHERE t.pk IS NULL` drops the ON condition. Wrong rows. | Primary key columns are NOT NULL. | +| ENG-30515 | INDEX COUNT clamps a bound above the column type's range to the type's maximum and misses rows holding it: TINYINT `c < 32767` does not count 127. | Constants in ordered numeric comparisons and BETWEEN lie between -126 and 126. | +| ENG-30516 | `WHERE c IS NULL AND c = 5` on an indexed column drops the IS NULL when `c = 5` becomes the index lookup. Wrong rows. | IS NULL is written `NOT (x IS NOT NULL)`. | + The published `voltdbclient` jar does not register its JDBC driver with `java.sql.Driver`, so the provider loads `org.voltdb.jdbc.Driver` itself. diff --git a/src/sqlancer/voltdb/VoltDBErrors.java b/src/sqlancer/voltdb/VoltDBErrors.java index e7cc93cb0..bcc8294f5 100644 --- a/src/sqlancer/voltdb/VoltDBErrors.java +++ b/src/sqlancer/voltdb/VoltDBErrors.java @@ -34,6 +34,26 @@ public static boolean isRetryable(SQLException e) { return false; } + public static void addExpressionErrors(ExpectedErrors errors) { + // VoltDB does not support a join whose WHERE clause folds to a filter on none of the joined tables; a + // predicate that references a column can still fold to a constant, e.g. (FALSE AND t.c) = FALSE + errors.add("Join with filters that do not depend on joined tables is not supported"); + // ENG-30508: the same rejected filter, when it is an IN with a DECIMAL constant on the left, fails with an + // internal error instead + errors.add("NUMERIC constant value type must match a FLOAT, DECIMAL, or integral column, not null"); + // run-time arithmetic errors: random operands divide by zero and overflow, and the two NoREC queries may + // evaluate an expression on different rows, so only one of them may hit the error + errors.add("Attempted to divide"); // integer or DECIMAL division by zero + errors.add("data exception: division by zero"); // the same, in constants the planner folds + errors.add("Invalid result value"); // FLOAT result is infinite or NaN + errors.add("will overflow BigInt storage"); // integer +, -, * out of range + errors.add("causing overflow/underflow"); // DECIMAL out of range + errors.add("out of range for the destination type"); // a huge DECIMAL or FLOAT result cast to an integer + // DECIMAL out of range in an expression of constants, which the planner folds; the message quotes a + // truncated value, e.g. "30145.999" for -99999999999999999999999999.999999999999 + -30146 + errors.add("Numeric conversion error to type DECIMAL"); + } + public static void addInsertErrors(ExpectedErrors errors) { // a generated key can repeat an existing primary key or unique value errors.add("CONSTRAINT VIOLATION"); diff --git a/src/sqlancer/voltdb/VoltDBOptions.java b/src/sqlancer/voltdb/VoltDBOptions.java index 48de45e68..a1fac275f 100644 --- a/src/sqlancer/voltdb/VoltDBOptions.java +++ b/src/sqlancer/voltdb/VoltDBOptions.java @@ -15,7 +15,7 @@ public class VoltDBOptions implements DBMSSpecificOptions { public static final int DEFAULT_PORT = 21212; @Parameter(names = "--oracle", description = "The test oracles to use") - public List oracles = List.of(VoltDBOracleFactory.SMOKE); + public List oracles = List.of(VoltDBOracleFactory.NOREC); @Parameter(names = "--max-num-tables", description = "The maximum number of tables each database creates") public int maxNumTables = 3; @@ -26,6 +26,9 @@ public class VoltDBOptions implements DBMSSpecificOptions { @Parameter(names = "--retry-seconds", description = "How long a statement VoltDB rejects because of a concurrent schema change is retried") public int retrySeconds = 120; + @Parameter(names = "--avoid-known-bugs", description = "Do not generate SQL that hits a known, unfixed VoltDB bug (see the README)", arity = 1) + public boolean avoidKnownBugs = true; + @Override public List getTestOracleFactory() { return oracles; diff --git a/src/sqlancer/voltdb/VoltDBOracleFactory.java b/src/sqlancer/voltdb/VoltDBOracleFactory.java index b18cc5979..fec4a2183 100644 --- a/src/sqlancer/voltdb/VoltDBOracleFactory.java +++ b/src/sqlancer/voltdb/VoltDBOracleFactory.java @@ -1,8 +1,11 @@ package sqlancer.voltdb; import sqlancer.OracleFactory; +import sqlancer.common.oracle.NoRECOracle; import sqlancer.common.oracle.TestOracle; +import sqlancer.common.query.ExpectedErrors; import sqlancer.voltdb.VoltDBProvider.VoltDBGlobalState; +import sqlancer.voltdb.gen.VoltDBExpressionGenerator; import sqlancer.voltdb.oracle.VoltDBSmokeOracle; public enum VoltDBOracleFactory implements OracleFactory { @@ -16,6 +19,19 @@ public enum VoltDBOracleFactory implements OracleFactory { public TestOracle create(VoltDBGlobalState globalState) { return new VoltDBSmokeOracle(globalState); } + }, + + /** + * Compares the row count of a query that filters with a random predicate in its WHERE clause with the count of an + * equivalent query that evaluates the predicate per row in its projection, which the planner cannot optimize. + */ + NOREC { + @Override + public TestOracle create(VoltDBGlobalState globalState) { + ExpectedErrors errors = ExpectedErrors.newErrors().build(); + VoltDBErrors.addExpressionErrors(errors); + return new NoRECOracle<>(globalState, new VoltDBExpressionGenerator(globalState), errors); + } } } diff --git a/src/sqlancer/voltdb/VoltDBToStringVisitor.java b/src/sqlancer/voltdb/VoltDBToStringVisitor.java new file mode 100644 index 000000000..968db321c --- /dev/null +++ b/src/sqlancer/voltdb/VoltDBToStringVisitor.java @@ -0,0 +1,67 @@ +package sqlancer.voltdb; + +import sqlancer.common.ast.newast.NewFunctionNode; +import sqlancer.common.ast.newast.NewToStringVisitor; +import sqlancer.voltdb.ast.VoltDBConstant; +import sqlancer.voltdb.ast.VoltDBExpression; +import sqlancer.voltdb.ast.VoltDBJoin; +import sqlancer.voltdb.ast.VoltDBSelect; + +public class VoltDBToStringVisitor extends NewToStringVisitor { + + @Override + public void visitSpecific(VoltDBExpression expr) { + if (expr instanceof VoltDBConstant) { + sb.append(expr.toString()); + } else if (expr instanceof VoltDBSelect) { + visit((VoltDBSelect) expr); + } else if (expr instanceof VoltDBJoin) { + visit((VoltDBJoin) expr); + } else { + throw new AssertionError(expr.getClass()); + } + } + + // ENG-30506: in a parenthesized AND/OR list, an operand that starts with a function call after an IN predicate + // crashes VoltDB's parser, e.g. (a IN (1) OR ABS(a) > 5); BETWEEN and IN print their left operand without + // parentheses, so a function call is always printed in parentheses + @Override + public void visit(NewFunctionNode funcCall) { + sb.append("("); + super.visit(funcCall); + sb.append(")"); + } + + private void visit(VoltDBJoin join) { + sb.append(' ').append(join.getJoinType()).append(" JOIN "); + visit((VoltDBExpression) join.getTable()); + sb.append(" ON "); + visit(join.getOnCondition()); + } + + private void visit(VoltDBSelect select) { + sb.append("SELECT "); + visit(select.getFetchColumns()); + sb.append(" FROM "); + // the joins attach to the last table of the FROM list, which is the one their ON conditions reference + visit(select.getFromList()); + for (VoltDBExpression join : select.getJoinList()) { + visit(join); + } + if (select.getWhereClause() != null) { + sb.append(" WHERE "); + visit(select.getWhereClause()); + } + if (!select.getOrderByClauses().isEmpty()) { + sb.append(" ORDER BY "); + visit(select.getOrderByClauses()); + } + } + + public static String asString(VoltDBExpression expr) { + VoltDBToStringVisitor visitor = new VoltDBToStringVisitor(); + visitor.visit(expr); + return visitor.get(); + } + +} diff --git a/src/sqlancer/voltdb/ast/VoltDBBetweenOperation.java b/src/sqlancer/voltdb/ast/VoltDBBetweenOperation.java new file mode 100644 index 000000000..9713ff6a5 --- /dev/null +++ b/src/sqlancer/voltdb/ast/VoltDBBetweenOperation.java @@ -0,0 +1,12 @@ +package sqlancer.voltdb.ast; + +import sqlancer.common.ast.newast.NewBetweenOperatorNode; + +public class VoltDBBetweenOperation extends NewBetweenOperatorNode implements VoltDBExpression { + + public VoltDBBetweenOperation(VoltDBExpression left, VoltDBExpression middle, VoltDBExpression right, + boolean isTrue) { + super(left, middle, right, isTrue); + } + +} diff --git a/src/sqlancer/voltdb/ast/VoltDBBinaryOperation.java b/src/sqlancer/voltdb/ast/VoltDBBinaryOperation.java new file mode 100644 index 000000000..490af712e --- /dev/null +++ b/src/sqlancer/voltdb/ast/VoltDBBinaryOperation.java @@ -0,0 +1,36 @@ +package sqlancer.voltdb.ast; + +import sqlancer.common.ast.BinaryOperatorNode.Operator; +import sqlancer.common.ast.newast.NewBinaryOperatorNode; + +public class VoltDBBinaryOperation extends NewBinaryOperatorNode implements VoltDBExpression { + + public enum VoltDBBinaryOperator implements Operator { + AND(" AND "), OR(" OR "), // + EQUALS(" = "), NOT_EQUALS(" <> "), SMALLER(" < "), SMALLER_EQUALS(" <= "), GREATER(" > "), + GREATER_EQUALS(" >= "), // + LIKE(" LIKE "), NOT_LIKE(" NOT LIKE "), // + ADD(" + "), SUBTRACT(" - "), MULTIPLY(" * "), DIVIDE(" / "), // + CONCAT(" || "); + + private final String text; + + VoltDBBinaryOperator(String text) { + this.text = text; + } + + @Override + public String getTextRepresentation() { + return text; + } + + public boolean isOrdering() { + return this == SMALLER || this == SMALLER_EQUALS || this == GREATER || this == GREATER_EQUALS; + } + } + + public VoltDBBinaryOperation(VoltDBExpression left, VoltDBExpression right, VoltDBBinaryOperator op) { + super(left, right, op); + } + +} diff --git a/src/sqlancer/voltdb/ast/VoltDBColumnReference.java b/src/sqlancer/voltdb/ast/VoltDBColumnReference.java new file mode 100644 index 000000000..c3ce264d0 --- /dev/null +++ b/src/sqlancer/voltdb/ast/VoltDBColumnReference.java @@ -0,0 +1,13 @@ +package sqlancer.voltdb.ast; + +import sqlancer.common.ast.newast.ColumnReferenceNode; +import sqlancer.voltdb.VoltDBSchema.VoltDBColumn; + +public class VoltDBColumnReference extends ColumnReferenceNode + implements VoltDBExpression { + + public VoltDBColumnReference(VoltDBColumn column) { + super(column); + } + +} diff --git a/src/sqlancer/voltdb/ast/VoltDBConstant.java b/src/sqlancer/voltdb/ast/VoltDBConstant.java new file mode 100644 index 000000000..7751c825a --- /dev/null +++ b/src/sqlancer/voltdb/ast/VoltDBConstant.java @@ -0,0 +1,17 @@ +package sqlancer.voltdb.ast; + +// A literal, written out as VoltDB SQL (see VoltDBConstantGenerator). +public class VoltDBConstant implements VoltDBExpression { + + private final String text; + + public VoltDBConstant(String text) { + this.text = text; + } + + @Override + public String toString() { + return text; + } + +} diff --git a/src/sqlancer/voltdb/ast/VoltDBExpression.java b/src/sqlancer/voltdb/ast/VoltDBExpression.java new file mode 100644 index 000000000..3cdcfd6d1 --- /dev/null +++ b/src/sqlancer/voltdb/ast/VoltDBExpression.java @@ -0,0 +1,8 @@ +package sqlancer.voltdb.ast; + +import sqlancer.common.ast.newast.Expression; +import sqlancer.voltdb.VoltDBSchema.VoltDBColumn; + +public interface VoltDBExpression extends Expression { + +} diff --git a/src/sqlancer/voltdb/ast/VoltDBFunction.java b/src/sqlancer/voltdb/ast/VoltDBFunction.java new file mode 100644 index 000000000..da766daf3 --- /dev/null +++ b/src/sqlancer/voltdb/ast/VoltDBFunction.java @@ -0,0 +1,19 @@ +package sqlancer.voltdb.ast; + +import java.util.List; + +import sqlancer.common.ast.newast.NewFunctionNode; + +public class VoltDBFunction extends NewFunctionNode + implements VoltDBExpression { + + // Functions the generator calls; the name is printed as written. + public enum VoltDBFunctionName { + ABS + } + + public VoltDBFunction(List args, VoltDBFunctionName func) { + super(args, func); + } + +} diff --git a/src/sqlancer/voltdb/ast/VoltDBInOperation.java b/src/sqlancer/voltdb/ast/VoltDBInOperation.java new file mode 100644 index 000000000..7672ff4d9 --- /dev/null +++ b/src/sqlancer/voltdb/ast/VoltDBInOperation.java @@ -0,0 +1,13 @@ +package sqlancer.voltdb.ast; + +import java.util.List; + +import sqlancer.common.ast.newast.NewInOperatorNode; + +public class VoltDBInOperation extends NewInOperatorNode implements VoltDBExpression { + + public VoltDBInOperation(VoltDBExpression left, List right, boolean isNegated) { + super(left, right, isNegated); + } + +} diff --git a/src/sqlancer/voltdb/ast/VoltDBJoin.java b/src/sqlancer/voltdb/ast/VoltDBJoin.java new file mode 100644 index 000000000..5125b5736 --- /dev/null +++ b/src/sqlancer/voltdb/ast/VoltDBJoin.java @@ -0,0 +1,46 @@ +package sqlancer.voltdb.ast; + +import sqlancer.Randomly; +import sqlancer.common.ast.newast.Join; +import sqlancer.voltdb.VoltDBSchema.VoltDBColumn; +import sqlancer.voltdb.VoltDBSchema.VoltDBTable; + +// One " JOIN table ON condition" in a FROM clause; it joins onto the FROM list before it. +public class VoltDBJoin implements VoltDBExpression, Join { + + public enum JoinType { + INNER, LEFT, RIGHT, FULL; + + public static JoinType getRandom() { + return Randomly.fromOptions(values()); + } + } + + private final VoltDBTableReference table; + private final JoinType joinType; + private VoltDBExpression onCondition; + + public VoltDBJoin(VoltDBTableReference table, JoinType joinType, VoltDBExpression onCondition) { + this.table = table; + this.joinType = joinType; + this.onCondition = onCondition; + } + + public VoltDBTableReference getTable() { + return table; + } + + public JoinType getJoinType() { + return joinType; + } + + public VoltDBExpression getOnCondition() { + return onCondition; + } + + @Override + public void setOnClause(VoltDBExpression onClause) { + this.onCondition = onClause; + } + +} diff --git a/src/sqlancer/voltdb/ast/VoltDBSelect.java b/src/sqlancer/voltdb/ast/VoltDBSelect.java new file mode 100644 index 000000000..1abdfd279 --- /dev/null +++ b/src/sqlancer/voltdb/ast/VoltDBSelect.java @@ -0,0 +1,30 @@ +package sqlancer.voltdb.ast; + +import java.util.List; +import java.util.stream.Collectors; + +import sqlancer.common.ast.SelectBase; +import sqlancer.common.ast.newast.Select; +import sqlancer.voltdb.VoltDBSchema.VoltDBColumn; +import sqlancer.voltdb.VoltDBSchema.VoltDBTable; +import sqlancer.voltdb.VoltDBToStringVisitor; + +public class VoltDBSelect extends SelectBase + implements VoltDBExpression, Select { + + @Override + public void setJoinClauses(List joinStatements) { + setJoinList(joinStatements.stream().map(j -> (VoltDBExpression) j).collect(Collectors.toList())); + } + + @Override + public List getJoinClauses() { + return getJoinList().stream().map(j -> (VoltDBJoin) j).collect(Collectors.toList()); + } + + @Override + public String asString() { + return VoltDBToStringVisitor.asString(this); + } + +} diff --git a/src/sqlancer/voltdb/ast/VoltDBTableReference.java b/src/sqlancer/voltdb/ast/VoltDBTableReference.java new file mode 100644 index 000000000..3451469ca --- /dev/null +++ b/src/sqlancer/voltdb/ast/VoltDBTableReference.java @@ -0,0 +1,13 @@ +package sqlancer.voltdb.ast; + +import sqlancer.common.ast.newast.TableReferenceNode; +import sqlancer.voltdb.VoltDBSchema.VoltDBTable; + +public class VoltDBTableReference extends TableReferenceNode + implements VoltDBExpression { + + public VoltDBTableReference(VoltDBTable table) { + super(table); + } + +} diff --git a/src/sqlancer/voltdb/ast/VoltDBUnaryPostfixOperation.java b/src/sqlancer/voltdb/ast/VoltDBUnaryPostfixOperation.java new file mode 100644 index 000000000..4685dcb57 --- /dev/null +++ b/src/sqlancer/voltdb/ast/VoltDBUnaryPostfixOperation.java @@ -0,0 +1,28 @@ +package sqlancer.voltdb.ast; + +import sqlancer.common.ast.BinaryOperatorNode.Operator; +import sqlancer.common.ast.newast.NewUnaryPostfixOperatorNode; + +public class VoltDBUnaryPostfixOperation extends NewUnaryPostfixOperatorNode + implements VoltDBExpression { + + public enum VoltDBUnaryPostfixOperator implements Operator { + IS_NULL("IS NULL"), IS_NOT_NULL("IS NOT NULL"); + + private final String text; + + VoltDBUnaryPostfixOperator(String text) { + this.text = text; + } + + @Override + public String getTextRepresentation() { + return text; + } + } + + public VoltDBUnaryPostfixOperation(VoltDBExpression expr, VoltDBUnaryPostfixOperator op) { + super(expr, op); + } + +} diff --git a/src/sqlancer/voltdb/ast/VoltDBUnaryPrefixOperation.java b/src/sqlancer/voltdb/ast/VoltDBUnaryPrefixOperation.java new file mode 100644 index 000000000..6bf6f1501 --- /dev/null +++ b/src/sqlancer/voltdb/ast/VoltDBUnaryPrefixOperation.java @@ -0,0 +1,28 @@ +package sqlancer.voltdb.ast; + +import sqlancer.common.ast.BinaryOperatorNode.Operator; +import sqlancer.common.ast.newast.NewUnaryPrefixOperatorNode; + +public class VoltDBUnaryPrefixOperation extends NewUnaryPrefixOperatorNode + implements VoltDBExpression { + + public enum VoltDBUnaryPrefixOperator implements Operator { + NOT("NOT"), MINUS("-"); + + private final String text; + + VoltDBUnaryPrefixOperator(String text) { + this.text = text; + } + + @Override + public String getTextRepresentation() { + return text; + } + } + + public VoltDBUnaryPrefixOperation(VoltDBExpression expr, VoltDBUnaryPrefixOperator op) { + super(expr, op); + } + +} diff --git a/src/sqlancer/voltdb/gen/VoltDBConstantGenerator.java b/src/sqlancer/voltdb/gen/VoltDBConstantGenerator.java index 646db6e49..9c9c6a659 100644 --- a/src/sqlancer/voltdb/gen/VoltDBConstantGenerator.java +++ b/src/sqlancer/voltdb/gen/VoltDBConstantGenerator.java @@ -93,7 +93,9 @@ private static String floatLiteral(Randomly r) { do { d = r.getFiniteDouble(); } while (d <= -Double.MAX_VALUE); - return Double.toString(d); + String s = Double.toString(d); + // without an exponent VoltDB reads the literal as a DECIMAL, which holds only 12 digits after the point + return s.contains("E") ? s : s + "E0"; } private static BigDecimal decimal(Randomly r) { diff --git a/src/sqlancer/voltdb/gen/VoltDBExpressionGenerator.java b/src/sqlancer/voltdb/gen/VoltDBExpressionGenerator.java new file mode 100644 index 000000000..0bc151a33 --- /dev/null +++ b/src/sqlancer/voltdb/gen/VoltDBExpressionGenerator.java @@ -0,0 +1,660 @@ +package sqlancer.voltdb.gen; + +import java.math.BigDecimal; +import java.util.ArrayList; +import java.util.List; +import java.util.function.Supplier; +import java.util.stream.Collectors; + +import sqlancer.IgnoreMeException; +import sqlancer.Randomly; +import sqlancer.common.gen.NoRECGenerator; +import sqlancer.common.gen.TypedExpressionGenerator; +import sqlancer.common.schema.AbstractTables; +import sqlancer.voltdb.VoltDBProvider.VoltDBGlobalState; +import sqlancer.voltdb.VoltDBSchema.VoltDBColumn; +import sqlancer.voltdb.VoltDBSchema.VoltDBCompositeDataType; +import sqlancer.voltdb.VoltDBSchema.VoltDBDataType; +import sqlancer.voltdb.VoltDBSchema.VoltDBTable; +import sqlancer.voltdb.VoltDBToStringVisitor; +import sqlancer.voltdb.ast.VoltDBBetweenOperation; +import sqlancer.voltdb.ast.VoltDBBinaryOperation; +import sqlancer.voltdb.ast.VoltDBBinaryOperation.VoltDBBinaryOperator; +import sqlancer.voltdb.ast.VoltDBColumnReference; +import sqlancer.voltdb.ast.VoltDBConstant; +import sqlancer.voltdb.ast.VoltDBExpression; +import sqlancer.voltdb.ast.VoltDBFunction; +import sqlancer.voltdb.ast.VoltDBFunction.VoltDBFunctionName; +import sqlancer.voltdb.ast.VoltDBInOperation; +import sqlancer.voltdb.ast.VoltDBJoin; +import sqlancer.voltdb.ast.VoltDBSelect; +import sqlancer.voltdb.ast.VoltDBTableReference; +import sqlancer.voltdb.ast.VoltDBUnaryPostfixOperation; +import sqlancer.voltdb.ast.VoltDBUnaryPostfixOperation.VoltDBUnaryPostfixOperator; +import sqlancer.voltdb.ast.VoltDBUnaryPrefixOperation; +import sqlancer.voltdb.ast.VoltDBUnaryPrefixOperation.VoltDBUnaryPrefixOperator; + +/** + * Typed expressions, and the queries the NoREC oracle compares. + * + *

+ * Every operand is generated for one {@link Kind}, so that VoltDB never rejects an expression for mixing types + * ("incompatible data types in combination"). NULL literals carry a type (CAST(NULL AS ...)), as VoltDB requires. + * + *

+ * VoltDB plans a query over several partitioned tables only when they are joined on their partitioning columns. The + * FROM clause therefore holds at most one partitioned table without a join condition; every other partitioned table is + * joined to it on the partitioning columns, and one whose partitioning column cannot be compared with it is left out. + * The join is in the FROM clause, so both NoREC queries have it. + */ +public final class VoltDBExpressionGenerator + extends TypedExpressionGenerator + implements NoRECGenerator { + + // The type classes VoltDB compares and combines freely within, and not across. + public enum Kind { + BOOLEAN, NUMERIC, STRING, VARBINARY, TEMPORAL; + + public static Kind fromType(VoltDBDataType type) { + switch (type) { + case BOOLEAN: + return BOOLEAN; + case TINYINT: + case SMALLINT: + case INTEGER: + case BIGINT: + case FLOAT: + case DECIMAL: + return NUMERIC; + case VARCHAR: + return STRING; + case VARBINARY: + return VARBINARY; + case TIMESTAMP: + case DATE: + return TEMPORAL; + default: + throw new AssertionError(type); + } + } + } + + private enum BooleanExpression { + COMPARISON, AND_OR, NOT, IS_NULL, BETWEEN, IN, LIKE + } + + private enum NumericDomain { + ANY, EXACT, FLOAT; + + boolean contains(VoltDBDataType type) { + return this == ANY || (type == VoltDBDataType.FLOAT) == (this == FLOAT); + } + } + + private enum NumericExpression { + UNARY_MINUS, ARITHMETIC, ABS + } + + private final VoltDBGlobalState state; + private final boolean avoidKnownBugs; + + // the FROM list, comma-separated; the joins attach to its last table + private List fromTables = new ArrayList<>(); + private List joins = new ArrayList<>(); + private boolean hasOuterJoin; + // ENG-30513: which numeric types the current comparison draws its operands from (see inNumericDomain) + private NumericDomain numericDomain = NumericDomain.ANY; + // how many comparison or IN operands enclose the expression being generated + private int comparandNesting; + + public VoltDBExpressionGenerator(VoltDBGlobalState state) { + this.state = state; + this.avoidKnownBugs = state.getDbmsSpecificOptions().avoidKnownBugs; + } + + @Override + protected VoltDBExpression generateExpression(Kind kind, int depth) { + if (depth >= state.getOptions().getMaxExpressionDepth() || Randomly.getBooleanWithSmallProbability()) { + return generateLeafNode(kind); + } + switch (kind) { + case BOOLEAN: + return generateBooleanExpression(depth); + case NUMERIC: + return generateNumericExpression(depth); + case STRING: + if (Randomly.getBoolean()) { + return new VoltDBBinaryOperation(generateExpression(Kind.STRING, depth + 1), + generateExpression(Kind.STRING, depth + 1), VoltDBBinaryOperator.CONCAT); + } + return generateLeafNode(kind); + default: + return generateLeafNode(kind); + } + } + + private VoltDBExpression generateBooleanExpression(int depth) { + switch (Randomly.fromOptions(BooleanExpression.values())) { + case COMPARISON: + Kind kind = getRandomType(); + VoltDBBinaryOperator op = Randomly.fromOptions(VoltDBBinaryOperator.EQUALS, VoltDBBinaryOperator.NOT_EQUALS, + VoltDBBinaryOperator.SMALLER, VoltDBBinaryOperator.SMALLER_EQUALS, VoltDBBinaryOperator.GREATER, + VoltDBBinaryOperator.GREATER_EQUALS); + if (op.isOrdering() && !canCompareOrdered(kind)) { + op = Randomly.fromOptions(VoltDBBinaryOperator.EQUALS, VoltDBBinaryOperator.NOT_EQUALS); + } + if (kind == Kind.VARBINARY && avoidKnownBugs) { + // ENG-12656: comparing a VARBINARY(n) column that leads a multi-column or unique index with a longer + // value fails, and the longer value can be another table's column; one side is a short constant + return new VoltDBBinaryOperation(generateComparand(kind, depth), generateConstant(kind, false), op); + } + VoltDBBinaryOperator comparison = op; + return inNumericDomain(kind, () -> { + if (kind == Kind.NUMERIC && comparison.isOrdering() && avoidKnownBugs) { + // ENG-30511: an index range scan on a narrower integer column with a key from a wider column that + // is below the narrower type's range matches every row; constant keys are handled correctly + return new VoltDBBinaryOperation(generateComparand(kind, depth), generateRangeBound(kind), + comparison); + } + return new VoltDBBinaryOperation(generateComparand(kind, depth), generateComparand(kind, depth), + comparison); + }); + case AND_OR: + return new VoltDBBinaryOperation(generateExpression(Kind.BOOLEAN, depth + 1), + generateExpression(Kind.BOOLEAN, depth + 1), + Randomly.fromOptions(VoltDBBinaryOperator.AND, VoltDBBinaryOperator.OR)); + case NOT: + VoltDBExpression negated = generateExpression(Kind.BOOLEAN, depth + 1); + if (avoidKnownBugs && negated instanceof VoltDBBinaryOperation && ((VoltDBBinaryOperation) negated) + .getOperatorRepresentation().equals(VoltDBBinaryOperator.OR.getTextRepresentation())) { + // ENG-30504: the planner fails on NOT (b OR c) over BOOLEAN values when it is an operand, as in + // NOT (NOT (b OR c)), (NOT (b OR c)) IS NOT NULL or (NOT (b OR c)) = TRUE + return negated; + } + return new VoltDBUnaryPrefixOperation(negated, VoltDBUnaryPrefixOperator.NOT); + case IS_NULL: + return generateIsNull(depth); + case BETWEEN: + Kind betweenKind; + do { + betweenKind = getRandomType(); + } while (!canCompareOrdered(betweenKind)); + if (avoidKnownBugs) { + // ENG-30511 as for comparisons, and ENG-30512: COUNT(*) over an empty index range, such as + // x BETWEEN 9 AND 1, is negative; the bounds are constants in ascending order + Kind boundsKind = betweenKind; + return inNumericDomain(boundsKind, () -> { + VoltDBConstant low = generateRangeBound(boundsKind); + VoltDBConstant high = generateRangeBound(boundsKind); + if (compareConstants(boundsKind, low, high) > 0) { + VoltDBConstant swap = low; + low = high; + high = swap; + } + return new VoltDBBetweenOperation(generateExpression(boundsKind, depth + 1), low, high, + Randomly.getBoolean()); + }); + } + return new VoltDBBetweenOperation(generateExpression(betweenKind, depth + 1), + generateExpression(betweenKind, depth + 1), generateExpression(betweenKind, depth + 1), + Randomly.getBoolean()); + case IN: + if (comparandNesting > 0) { + // VoltDB's parser rejects an IN predicate inside an operand of a comparison or IN, such as + // x = (y IN (1)): "unexpected token: IN" + return generateIsNull(depth); + } + if (hasOuterJoin && avoidKnownBugs) { + // ENG-30507: with an outer join, an IN predicate on an indexed column can be applied as part of the + // join instead of after it, so it does not remove the rows it should + return generateIsNull(depth); + } + Kind inKind = getRandomType(); + return inNumericDomain(inKind, () -> { + List list = new ArrayList<>(); + int n = 1 + Randomly.smallNumber(); + for (int i = 0; i < n; i++) { + list.add(generateInListElement(inKind, depth)); + } + return new VoltDBInOperation(generateComparand(inKind, depth), list, Randomly.getBoolean()); + }); + case LIKE: + return generateLike(depth); + default: + throw new AssertionError(); + } + } + + // An operand of a comparison or IN. ENG-30497: VoltDB turns an outer join into an inner join when the WHERE clause + // compares a boolean expression over the inner table, such as (t.c IS NULL) = TRUE, with something, although the + // comparison need not reject NULLs. With an outer join in the FROM clause, BOOLEAN operands are therefore only + // columns and constants, unless --avoid-known-bugs is false. + private VoltDBExpression generateComparand(Kind kind, int depth) { + if (kind == Kind.BOOLEAN && hasOuterJoin && avoidKnownBugs) { + return generateLeafNode(kind); + } + comparandNesting++; + try { + return generateExpression(kind, depth + 1); + } finally { + comparandNesting--; + } + } + + // ENG-30503: VoltDB ignores NULL elements of an IN list, so x NOT IN (NULL, ...) is TRUE instead of NULL + // (ENG-30500 is another wrong result with a NULL in the list). Unless --avoid-known-bugs is false, IN list + // elements are constants that are not NULL. + private VoltDBExpression generateInListElement(Kind kind, int depth) { + if (!avoidKnownBugs) { + return generateComparand(kind, depth); + } + return generateConstant(kind, false); + } + + // ENG-30513: comparing a FLOAT with a DECIMAL of magnitude 2^63 or more gives wrong results, and such DECIMALs come + // from the data and from arithmetic, not only constants. Unless --avoid-known-bugs is false, a numeric comparison, + // BETWEEN or IN draws all its operands from either FLOAT or the exact types (integers and DECIMAL). + private VoltDBExpression inNumericDomain(Kind kind, Supplier generator) { + if (kind != Kind.NUMERIC || !avoidKnownBugs || numericDomain != NumericDomain.ANY) { + return generator.get(); + } + numericDomain = Randomly.fromOptions(NumericDomain.EXACT, NumericDomain.FLOAT); + try { + return generator.get(); + } finally { + numericDomain = NumericDomain.ANY; + } + } + + private boolean isUsable(VoltDBColumn c, Kind kind) { + VoltDBDataType type = c.getType().getType(); + return Kind.fromType(type) == kind && (kind != Kind.NUMERIC || numericDomain.contains(type)); + } + + // A constant bound for an ordered comparison or BETWEEN. ENG-30515: INDEX COUNT clamps a bound outside the + // column type's range to the type's limit and then misses rows holding that limit (TINYINT c < 32767 does not + // count 127), so numeric bounds lie inside every integer type's range: -126 to 126. + private VoltDBConstant generateRangeBound(Kind kind) { + if (kind != Kind.NUMERIC) { + return (VoltDBConstant) generateConstant(kind, false); + } + Randomly r = state.getRandomly(); + long whole = r.getLong(-126, 127); + String text; + if (numericDomain == NumericDomain.FLOAT) { + text = whole + "." + r.getInteger(0, 1000) + "E0"; + } else if (Randomly.getBoolean()) { + text = whole + "." + r.getInteger(0, 1000); + } else { + text = Long.toString(whole); + } + return new VoltDBConstant(whole < 0 ? "(" + text + ")" : text); + } + + // Orders two NUMERIC or TEMPORAL constants as generateConstant writes them: a number, possibly in parentheses, or + // CAST('uuuu-MM-dd HH:mm:ss.SSSSSS' AS TIMESTAMP), whose text orders as the timestamp does. + private static int compareConstants(Kind kind, VoltDBConstant a, VoltDBConstant b) { + if (kind == Kind.NUMERIC) { + return new BigDecimal(a.toString().replaceAll("[()]", "")) + .compareTo(new BigDecimal(b.toString().replaceAll("[()]", ""))); + } + return a.toString().compareTo(b.toString()); + } + + // ENG-30497: with an outer join, (x IS NULL) IS NOT NULL and the like over the inner table turn the join into an + // inner join, so the operand is a column or a constant unless --avoid-known-bugs is false + // ENG-30516: WHERE c IS NULL AND c = 5 on an indexed column loses the IS NULL when c = 5 becomes the index lookup, + // so unless --avoid-known-bugs is false, IS NULL is written NOT (x IS NOT NULL), which VoltDB keeps. + private VoltDBExpression generateIsNull(int depth) { + Kind kind = getRandomType(); + VoltDBExpression operand = hasOuterJoin && avoidKnownBugs ? generateLeafNode(kind) + : generateExpression(kind, depth + 1); + VoltDBUnaryPostfixOperator op = Randomly.fromOptions(VoltDBUnaryPostfixOperator.values()); + if (op == VoltDBUnaryPostfixOperator.IS_NULL && avoidKnownBugs) { + return new VoltDBUnaryPrefixOperation( + new VoltDBUnaryPostfixOperation(operand, VoltDBUnaryPostfixOperator.IS_NOT_NULL), + VoltDBUnaryPrefixOperator.NOT); + } + return new VoltDBUnaryPostfixOperation(operand, op); + } + + // ENG-30493: VoltDB orders BOOLEAN values TRUE < FALSE where it evaluates them, so <, >, BETWEEN and ORDER BY on + // BOOLEAN values give wrong results; they are left out unless --avoid-known-bugs is false. + private boolean canOrder(Kind kind) { + return kind != Kind.BOOLEAN || !avoidKnownBugs; + } + + // ENG-30509 and ENG-12656: an index range scan on a VARCHAR(n) or VARBINARY(n) column compares it with only the + // first n characters of a longer value (wrong rows), or fails for VARBINARY. The longer value can be another + // table's column, so short constants do not avoid it: <, >, <=, >= and BETWEEN on strings and binary values are + // left out unless --avoid-known-bugs is false. ORDER BY is not affected. + private boolean canCompareOrdered(Kind kind) { + return canOrder(kind) && (!avoidKnownBugs || kind != Kind.STRING && kind != Kind.VARBINARY); + } + + private VoltDBExpression generateNumericExpression(int depth) { + switch (Randomly.fromOptions(NumericExpression.values())) { + case UNARY_MINUS: + if (avoidKnownBugs) { + // ENG-30502: unary minus on a NULL integer or FLOAT gives a non-NULL value; 0 - x does not + return new VoltDBBinaryOperation(new VoltDBConstant("0"), generateExpression(Kind.NUMERIC, depth + 1), + VoltDBBinaryOperator.SUBTRACT); + } + return new VoltDBUnaryPrefixOperation(generateExpression(Kind.NUMERIC, depth + 1), + VoltDBUnaryPrefixOperator.MINUS); + case ARITHMETIC: + return new VoltDBBinaryOperation(generateExpression(Kind.NUMERIC, depth + 1), + generateExpression(Kind.NUMERIC, depth + 1), Randomly.fromOptions(VoltDBBinaryOperator.ADD, + VoltDBBinaryOperator.SUBTRACT, VoltDBBinaryOperator.MULTIPLY, VoltDBBinaryOperator.DIVIDE)); + case ABS: + return new VoltDBFunction(List.of(generateExpression(Kind.NUMERIC, depth + 1)), VoltDBFunctionName.ABS); + default: + throw new AssertionError(); + } + } + + // ENG-30496: inside CASE WHEN, which is where NoREC's unoptimized query puts the predicate, VoltDB's planner + // crashes on a LIKE with a constant left operand, or with a pattern that has no wildcard or is just '%'. Unless + // --avoid-known-bugs is false, the left operand is a string column and the pattern has a wildcard and a literal + // character. + private VoltDBExpression generateLike(int depth) { + VoltDBBinaryOperator op = Randomly.fromOptions(VoltDBBinaryOperator.LIKE, VoltDBBinaryOperator.NOT_LIKE); + if (!avoidKnownBugs) { + return new VoltDBBinaryOperation(generateExpression(Kind.STRING, depth + 1), + Randomly.getBoolean() ? generateLikePattern() : generateExpression(Kind.STRING, depth + 1), op); + } + if (!canGenerateColumnOfType(Kind.STRING)) { + return generateIsNull(depth); + } + return new VoltDBBinaryOperation(generateColumn(Kind.STRING), generateLikePattern(), op); + } + + // A LIKE pattern: a random string with wildcards mixed in, keeping at least one wildcard and one other character. + private VoltDBExpression generateLikePattern() { + String s = state.getRandomly().getString().replace("%", "").replace("_", ""); + if (s.isEmpty()) { + s = state.getRandomly().getAlphabeticChar(); + } + StringBuilder sb = new StringBuilder(); + boolean wildcard = false; + for (int i = 0; i < s.length(); i++) { + // ENG-30509: VoltDB scans an index for the literal prefix of the pattern, which must be at most one + // character (see generateConstant) + if (i == 1 && avoidKnownBugs && !wildcard || Randomly.getBooleanWithRatherLowProbability()) { + sb.append(Randomly.fromOptions("%", "_")); + wildcard = true; + } + sb.append(s.charAt(i)); + } + if (!wildcard || Randomly.getBoolean()) { + sb.append(Randomly.fromOptions("%", "_")); + } + return new VoltDBConstant("'" + sb.toString().replace("'", "''") + "'"); + } + + @Override + public VoltDBExpression generateConstant(Kind kind) { + return generateConstant(kind, true); + } + + private VoltDBExpression generateConstant(Kind kind, boolean mayBeNull) { + VoltDBDataType type = randomDataType(kind); + if (kind == Kind.TEMPORAL && avoidKnownBugs) { + // ENG-30499: the planner crashes folding a comparison of a DATE constant with a TIMESTAMP constant + type = VoltDBDataType.TIMESTAMP; + } + // ENG-30495: a WHERE clause that folds to a constant NULL crashes the planner, and only NULL literals can make + // it fold to NULL (ENG-30500 and ENG-30503 are wrong results with NULLs in IN lists). Unless + // --avoid-known-bugs is false, queries get their NULLs from the data only. + if (mayBeNull && !avoidKnownBugs && Randomly.getBooleanWithRatherLowProbability()) { + // VoltDB needs a typed NULL: a bare NULL is "data type cast needed for parameter or null literal" + return new VoltDBConstant("CAST(NULL AS " + type + ")"); + } + if (kind == Kind.BOOLEAN && avoidKnownBugs) { + // ENG-30494: VoltDB passes BOOLEAN literals to the EE as parameters of the wrong value or type, giving + // cast errors and wrong rows; a comparison of integers is a boolean constant without a BOOLEAN literal + return new VoltDBConstant(Randomly.getBoolean() ? "(1 = 1)" : "(1 = 0)"); + } + if (kind == Kind.STRING && avoidKnownBugs) { + // ENG-30509: a range scan on a multi-column index compares a VARCHAR(n) column with only the first n + // characters of a longer value, and ENG-30505 is an error for IN on a unique index; the smallest generated + // VARCHAR column holds one character + String str = state.getRandomly().getString(); + if (str.codePointCount(0, str.length()) > 1) { + str = str.substring(0, str.offsetByCodePoints(0, 1)); + } + return new VoltDBConstant("'" + str.replace("'", "''") + "'"); + } + if (kind == Kind.VARBINARY && avoidKnownBugs) { + // ENG-12656: an index scan for <, <=, >, >= or BETWEEN on a VARBINARY(n) column fails ("Type VARCHAR can't + // be cast as VARBINARY") when the value is longer than n bytes, and ENG-30505 is the same for IN on a + // unique + // index; the smallest generated VARBINARY column holds one byte + byte[] bytes = state.getRandomly().getBytes(); + return new VoltDBConstant(bytes.length == 0 ? "x''" : String.format("x'%02X'", bytes[0])); + } + String literal = VoltDBConstantGenerator.generate(state.getRandomly(), VoltDBCompositeDataType.getRandom(type)); + if (kind == Kind.TEMPORAL) { + // a string literal compares with TIMESTAMP and DATE values, but not inside an IN list + return new VoltDBConstant("CAST(" + literal + " AS " + type + ")"); + } + if (literal.startsWith("-")) { + // VoltDB's parser rejects "- -5", which the unary minus would otherwise produce + return new VoltDBConstant("(" + literal + ")"); + } + return new VoltDBConstant(literal); + } + + private VoltDBDataType randomDataType(Kind kind) { + switch (kind) { + case BOOLEAN: + return VoltDBDataType.BOOLEAN; + case NUMERIC: + VoltDBDataType type; + do { + type = Randomly.fromOptions(VoltDBDataType.TINYINT, VoltDBDataType.SMALLINT, VoltDBDataType.INTEGER, + VoltDBDataType.BIGINT, VoltDBDataType.FLOAT, VoltDBDataType.DECIMAL); + } while (!numericDomain.contains(type)); + return type; + case STRING: + return VoltDBDataType.VARCHAR; + case VARBINARY: + return VoltDBDataType.VARBINARY; + case TEMPORAL: + return Randomly.fromOptions(VoltDBDataType.TIMESTAMP, VoltDBDataType.DATE); + default: + throw new AssertionError(kind); + } + } + + @Override + protected VoltDBExpression generateColumn(Kind kind) { + return new VoltDBColumnReference( + Randomly.fromList(columns.stream().filter(c -> isUsable(c, kind)).collect(Collectors.toList()))); + } + + @Override + protected Kind getRandomType() { + return Randomly.fromOptions(Kind.values()); + } + + @Override + protected boolean canGenerateColumnOfType(Kind kind) { + return columns.stream().anyMatch(c -> isUsable(c, kind)); + } + + @Override + public VoltDBExpressionGenerator setTablesAndColumns(AbstractTables tables) { + fromTables = new ArrayList<>(); + joins = new ArrayList<>(); + hasOuterJoin = false; + List partitionJoined = new ArrayList<>(); + VoltDBTable anchor = null; + for (VoltDBTable t : tables.getTables()) { + if (!t.isPartitioned()) { + fromTables.add(t); + } else if (anchor == null) { + anchor = t; + } else if (canPartitionJoin(anchor, t)) { + partitionJoined.add(t); + } + // a partitioned table whose partitioning column cannot be compared with the anchor's is left out + } + if (anchor == null) { + anchor = fromTables.remove(fromTables.size() - 1); + } + List explicitlyJoined = new ArrayList<>(); + for (VoltDBTable t : new ArrayList<>(fromTables)) { + if (Randomly.getBooleanWithRatherLowProbability()) { + fromTables.remove(t); + explicitlyJoined.add(t); + } + } + fromTables.add(anchor); + + List all = new ArrayList<>(); + fromTables.forEach(t -> all.addAll(t.getColumns())); + for (VoltDBTable t : partitionJoined) { + joins.add(new VoltDBJoin(new VoltDBTableReference(t), randomJoinType(), partitionJoinCondition(anchor, t))); + all.addAll(t.getColumns()); + } + for (VoltDBTable t : explicitlyJoined) { + joins.add(new VoltDBJoin(new VoltDBTableReference(t), randomJoinType(), joinCondition(anchor, t))); + all.addAll(t.getColumns()); + } + this.columns = all; + hasOuterJoin = joins.stream().anyMatch(j -> j.getJoinType() != VoltDBJoin.JoinType.INNER); + return this; + } + + // ENG-30510: VoltDB turns a RIGHT JOIN into a LEFT JOIN and can then use an ON condition on the preserved table + // as its index range, dropping rows; unless --avoid-known-bugs is false, joins are INNER, LEFT or FULL (a RIGHT + // JOIN is a LEFT JOIN with the tables swapped) + private VoltDBJoin.JoinType randomJoinType() { + if (avoidKnownBugs) { + return Randomly.fromOptions(VoltDBJoin.JoinType.INNER, VoltDBJoin.JoinType.LEFT, VoltDBJoin.JoinType.FULL); + } + return VoltDBJoin.JoinType.getRandom(); + } + + // ENG-12656: an index lookup on a VARBINARY(n) column fails for a longer value, so unless --avoid-known-bugs is + // false, VARBINARY partitioning columns are joined only when they have the same size + private boolean canPartitionJoin(VoltDBTable anchor, VoltDBTable t) { + if (partitionKind(t) != partitionKind(anchor)) { + return false; + } + return partitionKind(t) != Kind.VARBINARY || !avoidKnownBugs + || partitionColumn(t).getType().getSize() == partitionColumn(anchor).getType().getSize(); + } + + private static Kind partitionKind(VoltDBTable t) { + return Kind.fromType(t.getColumns().stream().filter(c -> c.getName().equals(t.getPartitionColumn())).findFirst() + .orElseThrow(() -> new AssertionError(t.getName())).getType().getType()); + } + + // anchor.pc = t.pc and nothing else: VoltDB plans a join of partitioned tables only when it can see the equality + // of their partitioning columns, and a further condition that folds to FALSE, such as pc = pc AND (1 = 0), takes + // the equality with it ("This query is not plannable"). Random join conditions are left to replicated tables. + private static VoltDBExpression partitionJoinCondition(VoltDBTable anchor, VoltDBTable t) { + return new VoltDBBinaryOperation(new VoltDBColumnReference(partitionColumn(anchor)), + new VoltDBColumnReference(partitionColumn(t)), VoltDBBinaryOperator.EQUALS); + } + + private static VoltDBColumn partitionColumn(VoltDBTable t) { + return t.getColumns().stream().filter(c -> c.getName().equals(t.getPartitionColumn())).findFirst() + .orElseThrow(() -> new AssertionError(t.getName())); + } + + // a random condition over the columns of the two tables + private VoltDBExpression joinCondition(VoltDBTable anchor, VoltDBTable t) { + List joinColumns = new ArrayList<>(anchor.getColumns()); + joinColumns.addAll(t.getColumns()); + VoltDBExpressionGenerator gen = new VoltDBExpressionGenerator(state).setColumns(joinColumns); + return gen.generatePredicateWithColumn(); + } + + @Override + public VoltDBExpression generatePredicate() { + return generateExpression(Kind.BOOLEAN); + } + + @Override + public VoltDBExpression negatePredicate(VoltDBExpression predicate) { + return new VoltDBUnaryPrefixOperation(predicate, VoltDBUnaryPrefixOperator.NOT); + } + + @Override + public VoltDBExpression isNull(VoltDBExpression expr) { + return new VoltDBUnaryPostfixOperation(expr, VoltDBUnaryPostfixOperator.IS_NULL); + } + + // A WHERE predicate always references a column. VoltDB does not support a join filter that depends on none of the + // joined tables, and its planner crashes on a WHERE clause that folds to a constant NULL (ENG-30495). + @Override + public VoltDBExpression generateBooleanExpression() { + return generatePredicateWithColumn(); + } + + private VoltDBExpression generatePredicateWithColumn() { + for (int i = 0; i < 100; i++) { + VoltDBExpression predicate = generateExpression(Kind.BOOLEAN); + String text = VoltDBToStringVisitor.asString(predicate); + if (columns.stream().anyMatch(c -> text.contains(c.getFullQualifiedName()))) { + return predicate; + } + } + throw new IgnoreMeException(); + } + + @Override + public VoltDBSelect generateSelect() { + return new VoltDBSelect(); + } + + @Override + public List getRandomJoinClauses() { + return joins; + } + + @Override + public List getTableRefs() { + return fromTables.stream().map(VoltDBTableReference::new).collect(Collectors.toList()); + } + + @Override + public String generateOptimizedQueryString(VoltDBSelect select, VoltDBExpression whereCondition, + boolean shouldUseAggregate) { + if (shouldUseAggregate) { + select.setFetchColumns(List.of(new VoltDBConstant("COUNT(*)"))); + } else { + select.setFetchColumns(columns.stream().map(VoltDBColumnReference::new).collect(Collectors.toList())); + if (Randomly.getBooleanWithSmallProbability()) { + select.setOrderByClauses(generateOrderBys()); + } + } + select.setWhereClause(whereCondition); + return select.asString(); + } + + @Override + public List generateOrderBys() { + List orderable = columns.stream().filter(c -> canOrder(Kind.fromType(c.getType().getType()))) + .collect(Collectors.toList()); + if (orderable.isEmpty()) { + return List.of(); + } + return Randomly.nonEmptySubset(orderable).stream().map(VoltDBColumnReference::new).collect(Collectors.toList()); + } + + @Override + public String generateUnoptimizedQueryString(VoltDBSelect select, VoltDBExpression whereCondition) { + // The predicate moves from WHERE into the projection, where the planner cannot use it to filter. CASE counts + // a row only when the predicate is TRUE, as WHERE does. COALESCE turns the SUM of no rows (NULL) into 0. + select.setFetchColumns(List.of(new VoltDBConstant( + "CASE WHEN " + VoltDBToStringVisitor.asString(whereCondition) + " THEN 1 ELSE 0 END AS c"))); + select.setWhereClause(null); + select.setOrderByClauses(List.of()); + return "SELECT COALESCE(SUM(c), 0) FROM (" + select.asString() + ") AS res"; + } + +} diff --git a/src/sqlancer/voltdb/gen/VoltDBTableGenerator.java b/src/sqlancer/voltdb/gen/VoltDBTableGenerator.java index 1b08cda9b..3c674cae5 100644 --- a/src/sqlancer/voltdb/gen/VoltDBTableGenerator.java +++ b/src/sqlancer/voltdb/gen/VoltDBTableGenerator.java @@ -57,14 +57,26 @@ public static SQLQueryAdapter getQuery(VoltDBGlobalState globalState) { partitionColumn.notNull = true; } + List primaryKey = null; + if (Randomly.getBooleanWithRatherLowProbability() || Randomly.getBoolean()) { + primaryKey = keyColumns(columns, partitionColumn, true); + if (globalState.getDbmsSpecificOptions().avoidKnownBugs) { + // ENG-30514: VoltDB stores NULL in a primary key column that is not declared NOT NULL, but its + // planner assumes such a column is never NULL, which gives wrong rows for outer joins + primaryKey.forEach(c -> c.notNull = true); + } + } + List uniqueKey = Randomly.getBooleanWithRatherLowProbability() + ? keyColumns(columns, partitionColumn, false) : null; + StringBuilder sb = new StringBuilder("CREATE TABLE ").append(table).append(" ("); sb.append(columns.stream().map(c -> c.name + " " + c.type + (c.notNull ? " NOT NULL" : "")) .collect(Collectors.joining(", "))); - if (Randomly.getBooleanWithRatherLowProbability() || Randomly.getBoolean()) { - appendKey(sb, columns, partitionColumn, true); + if (primaryKey != null) { + appendKey(sb, primaryKey, partitionColumn, true); } - if (Randomly.getBooleanWithRatherLowProbability()) { - appendKey(sb, columns, partitionColumn, false); + if (uniqueKey != null) { + appendKey(sb, uniqueKey, partitionColumn, false); } sb.append(");"); if (partitionColumn != null) { @@ -73,14 +85,18 @@ public static SQLQueryAdapter getQuery(VoltDBGlobalState globalState) { return new SQLQueryAdapter(sb.toString(), ExpectedErrors.newErrors().build(), true); } - // Appends PRIMARY KEY (primary) or a UNIQUE / ASSUMEUNIQUE constraint over a random column subset. - private static void appendKey(StringBuilder sb, List columns, Column partitionColumn, boolean primary) { + // A random column subset for a key; a primary key always includes the partitioning column. + private static List keyColumns(List columns, Column partitionColumn, boolean primary) { List key = new ArrayList<>(Randomly.nonEmptySubset(columns)); - boolean hasPartitionColumn = partitionColumn == null || key.contains(partitionColumn); - if (primary && !hasPartitionColumn) { + if (primary && partitionColumn != null && !key.contains(partitionColumn)) { key.add(partitionColumn); - hasPartitionColumn = true; } + return key; + } + + // Appends PRIMARY KEY (primary) or a UNIQUE / ASSUMEUNIQUE constraint over the key columns. + private static void appendKey(StringBuilder sb, List key, Column partitionColumn, boolean primary) { + boolean hasPartitionColumn = partitionColumn == null || key.contains(partitionColumn); sb.append(", "); if (primary) { sb.append("PRIMARY KEY"); diff --git a/test/sqlancer/dbms/TestVoltDB.java b/test/sqlancer/dbms/TestVoltDB.java index b4cd313d2..e4dd945d9 100644 --- a/test/sqlancer/dbms/TestVoltDB.java +++ b/test/sqlancer/dbms/TestVoltDB.java @@ -19,4 +19,13 @@ public void testVoltDBSmoke() { "--oracle", "SMOKE" })); } + @Test + public void testVoltDBNoREC() { + assumeTrue(TestConfig.isEnvironmentTrue(TestConfig.VOLTDB_ENV)); + assertEquals(0, + Main.executeMain(new String[] { "--random-seed", "0", "--timeout-seconds", TestConfig.SECONDS, + "--num-threads", "2", "--num-queries", "100", "--username", "", "--password", "", "voltdb", + "--oracle", "NOREC" })); + } + }