DRILL-8537: Bump Calcite to Version 1.42 - #3025
Conversation
Major Changes1. Function Type InferenceEXTRACT FunctionProblem: EXTRACT(SECOND) was returning BIGINT instead of DOUBLE, losing fractional seconds
Files Modified:
TIMESTAMPDIFF FunctionProblem: Type mismatch between validation (BIGINT) and conversion (INTEGER)
Files Modified:
TIMESTAMPADD FunctionProblem: Calcite 1.35 was adding precision to DATE types, causing assertion errors
Files Modified:
2. Function Registration & ResolutionVararg Functions (CONCAT, COALESCE, etc.)Problem: Function resolution failures for functions with variable arguments Files Modified:
Niladic Special Functions (CURRENT_DATE, SESSION_USER, etc.)Problem: Special functions not properly recognized in Calcite 1.35
Files Modified:
3. COUNT(*) HandlingProblem: COUNT(*) type inference changed in Calcite 1.35 Files Modified:
4. Aggregate Cost EstimationProblem: Deprecated Files Modified:
5. TIMESTAMPADD ImplementationProblem: Complete signature change in Calcite 1.35
Files Modified:
6. Complex Writer FunctionsProblem: FLATTEN, CONVERT_FROM, CONVERT_TO require ProjectRecordBatch context
Files Modified:
7. FLATTEN in Aggregates ValidationProblem: FLATTEN only validated in COUNT, allowed in other aggregates Files Modified:
8. Error Handling & ValidationPrepared Statement ErrorsProblem: Parse errors wrapped differently in RPC layer, appearing as SYSTEM instead of VALIDATION
Files Modified:
Invalid CAST OperationsProblem: Calcite 1.35 correctly rejects semantically invalid CAST(DATE as TIME) Files Modified:
Test UpdatesCore Module Tests
JDBC Storage Plugin Tests
Key Behavioral ChangesType Inference
Function Resolution
Validation
Files CreatedCore Engine
Tests
Migration Notes for DevelopersIf you use EXTRACT(SECOND):
If you use COUNT(*):
If you use SQRT or math functions:
If you cast DATE to TIME:
CompatibilityBackward Compatibility
Breaking Changes
|
b1599a1 to
de8803d
Compare
f2e4fc5 to
981bafb
Compare
3d407f2 to
b9b3e59
Compare
…1.37 This commit fixes the cartesian join error that occurs with INTERSECT/UNION queries containing scalar subqueries like 'SELECT 1' in Calcite 1.37.0. Changes to JoinUtils.java: 1. Enhanced isScalarSubquery() method to detect scalar subqueries represented as Values nodes: - Added support for org.apache.calcite.rel.logical.LogicalValues - Added support for org.apache.drill.exec.planner.common.DrillValuesRelBase - Both check if tuples.size() <= 1 to identify scalar subqueries 2. Modified checkCartesianJoin() method to allow cartesian joins with scalar subqueries: - Added hasScalarSubqueryInput() checks for both INNER and non-INNER joins - Returns false (not a problematic cartesian join) when a scalar subquery is detected - Allows nested loop joins for scalar subqueries instead of throwing errors Reverted problematic changes: - DrillRexBuilder.java: Removed ensureType() override that added casts for nullability - DrillRelFactories.java: Removed nullability normalization in FilterFactory - DefaultSqlHandler.java: Removed extra logging Test results: - TestSetOp tests (testIntersectCancellation, testUnionFilterPushDownOverOr): PASSING - TestJoinNullable tests: PASSING - No regression in other tests
eb6644d to
b77ad2b
Compare
DRILL-8537: Bump Calcite to Version 1.42
Description
I am attempting a new approach and instead of bumping Calcite from 1.34 -> 1.40, I'm going to try this one version at a time and see how far we get.
After reaching a known-good 1.38 (all unit tests passing), the remaining bump was done in a single step from 1.38 → 1.42 (skipping the 1.39 regressions, which are resolved by 1.42). Avatica was bumped 1.23 → 1.28 to match Calcite 1.42.
Current Status:
Significant Changes in Calcite 1.35
literal_aggfunction which allows literals in aggregate queries.VARDECIMALhandling.Significant Changes in Calcite 1.36
There are no significant changes in Calcite 1.36.
Significant Changes in Calcite 1.37
Significant Changes in Calcite 1.38
DrillSqlToRelConverterfor graceful handling of Calcite 1.38's strict type checkingASOFjoins, but Drill does not yet support that yet.Significant Changes in Calcite 1.39 – 1.42
Bumped directly from 1.38 to 1.42 (with Avatica 1.23 → 1.28). The notable breaking changes and how Drill adapts to them:
Schema resolution rewritten to a
LookupAPI (CALCITE-6029, 1.39).CalciteSchemano longer exposesgetImplicitSubSchema/getImplicitTable; sub-schema and table resolution now go throughsubSchemas()/tables()Lookups.DynamicSchema/DynamicRootSchemawere rewritten accordingly:subSchemas(). BothgetandgetIgnoreCasetrigger the lazy load, so single-identifier multi-level names such as`cp.default`/`dfs.tmp`keep working.tables().AbstractSchema(the base for every storage-plugin schema) also overridessubSchemas(). Calcite 1.42's default case-insensitivegetIgnoreCasematches only againstgetSubSchemaNames(), but several plugins expose sub-schemas lazily viagetSubSchema(name)without enumerating them (Cassandra keyspaces, Mongo databases, …). The override keeps the default name-based match and adds a lazygetSubSchema(name)fallback, so multi-level references likecassandra.test_keyspace.employeeresolve again (these regressed toObject 'test_keyspace' not found within 'cassandra'). Enumerated schemas are unaffected since the name-based match wins first.RexVisitor.visitNodeAndFieldIndex(1.41). Implemented inJdbcExpressionCheck(the only directRexVisitorimplementation); all other visitors extendRexVisitorImpland inherit the default.Type-system methods made
final(1.42).RelDataTypeSystem.getMaxNumericPrecision()/getMaxNumericScale()are nowfinal; removed Drill's overrides — the logic already lives ingetMaxPrecision/getMaxScale(which Drill overrides to 38 forDECIMAL).Window output column naming (1.42). Calcite no longer names window-function output columns
w<group>$....WindowPrulenow selects each group's output fields positionally (after the input fields) instead of by name prefix; the old name-based filter silently dropped all window columns, producing "field sizes are not equal".TRIMgrammar (1.42).CalciteResource.illegalFromEmpty()was removed;Parser.jjraises aParseExceptionforTRIM(FROM x)while preserving Drill'sTRIM(<flag> <chars>)extension.Avatica 1.28.
Cursor.Accessorgained unsigned accessors (getUByte/getUShort/getUInt/getULong, returning jOOU types) andAvaticaSite.getgained asignedparameter. Implemented the unsigned accessors inAvaticaDrillSqlAccessor(Drill has only signed types, so they mirror the signed getters) and passsigned=true.Stronger plan-time constant reduction. Calcite 1.42 reduces more aggressively and builds
Sargs during predicate inference, which surfaced two issues inDrillConstExecutor:DATE + INTERVAL YEARis typedDATEby Calcite but computed as aTIMESTAMPby Drill; folding it to aTIMESTAMPliteral then landing in aDATESargfailed withTimestampString cannot be cast to DateString. The executor now emits aDATEliteral whenever Calcite types the expression asDATE.CHARconstants make Drill's interpreter return no value; the executor now leaves such expressions unfolded instead of NPE-ing.ROW()in a constant context (1.42).DrillOptiq'sROWhandling built field-name literals viagetRexBuilder(), which is null when converting a standalone (constant-folded) expression; it now builds the Drill string literal directly.LIKE ... ESCAPEwhen the escape character is a wildcard. Calcite 1.42'sRexSimplify.simplifyLikemishandles aLIKEwhoseESCAPEcharacter is also a wildcard ('%'/'_') — it collapses the escaped wildcard and produces an altered pattern. Filter-expression reduction is skipped when the condition contains such aLIKE, preserving the original pattern.Constant
VALUEScollation. Calcite 1.42 derives collations for constant/single-rowVALUESand propagates them. Drill applies ordering in a later physical phase and has no logical collation-conversion rules, so this causedCannotPlanException: ... sort=[...]. Derived collations are stripped before logical Volcano planning; aSort's own collation (an explicitORDER BY) is preserved.GROUP BY by alias. Calcite 1.42 stopped expanding
GROUP BYitems that reference a SELECT alias (it still does forHAVING), soGROUP BY <alias>failed validation even thoughDrillConformance.isGroupByAlias()istrue. A pre-validationGroupByAliasRewriterrestores the behavior.BOOLEANin arithmetic. Calcite 1.42 coercesBOOLEANto a numeric type in arithmetic, emitting casts (e.g.castINT(BIT)) that Drill did not implement. AddedBit -> Int/BigInt/Float4/Float8cast functions (true -> 1,false -> 0).ORDER BY validation performance (wide queries). Calcite 1.42's
validateOrderListcallsisAggregate(select)once for every ORDER BY item (viaOrderExpressionExpander → nthSelectItem → expandSelectItem), and each call rescans the entire SELECT list withAggFinder. For wide queries this isO(orderByItems × selectListSize)—TestLargeFileCompilation's 2500-column projection ordered by 500 columns took >200s to validate and timed out. SinceisAggregatedepends only on GROUP BY / HAVING / the SELECT list (none of which change during ORDER BY expansion),DrillSqlValidatornow memoizes it per SELECT node by identity. Planning a 1600×320 query drops from ~127s to ~2.5s.Constant propagation into projections over ANY columns. Under schema-on-read a scan column is typed
ANYand=is an implicit-cast comparison, not a type-strict equality. Calcite 1.42 propagates equality constants from pulled-up predicates more aggressively, so a query likeSELECT float ... WHERE float = '1.2'rewrote the projectedANYfloatcolumn into the comparedVARCHARliteral and returned the string"1.2"instead of the double1.2. Both project reduce rules (DrillReduceExpressionsRuleandReduceAndSimplifyExpressionsRules) now stripANY-column equality predicates before simplifying, so the column keeps its real (FLOAT8) type.Degenerate cartesian joins in set-op-in-
WITHtests. Some TPC-DS-derived tests (TestSetOp.testIntersectWith,TestUnionAll.testUnionAllInWith) self-join on a constant literal column (year_total = year_total), which is a genuine cartesian join. Calcite 1.42 correctly folds the constant join key and identifies the cartesian (earlier versions kept a redundant equi-join), so those queries now require Drill's non-scalar nested-loop join — the tests enableplanner.enable_nljoin_for_scalar_only=falsefor the affected queries.Other behavioral notes (test baselines updated):
DECIMAL(38,4)) rather than dropping integer digits (DECIMAL(38,6)).Documentation
No user facing changes.
Testing
Ran existing unit tests.