Skip to content

[FEATURE] Unified SQL language across OpenSearch, Flint and Spark SQL #5346

Open

Description

@dai-chen

Is your feature request related to a problem?

OpenSearch SQL is currently fragmented across two repositories and four engines. This fragmentation creates the same class of problems identified in the PPL unification effort (opensearch-project/opensearch-spark#1136): semantic divergence, engineering duplication, feature lag, and missed optimization opportunities.

Repository Engine Scope
opensearch-project/sql Legacy (NLPchina) JOINs, UNIONs, subqueries
opensearch-project/sql V2 Simple queries, improved correctness
opensearch-project/sql Calcite-based ANSI SQL (new) Analytics engine integration, ANSI SQL compliance
opensearch-project/opensearch-spark Spark SQL + Flint SQL Spark queries, secondary index DDL

A gap analysis that runs the full V2 + Legacy integration test suite (807 queries) against the new Calcite engine shows a 67.9% pass rate, with 259 failures across 13 categories. This quantifies the distance between the current engines and a unified SQL baseline. See #5346 (comment) below for the full breakdown.

What solution would you like?

Define a Unified SQL Language specification — an ANSI SQL core with internal language extensions that model capabilities such as custom identifier/parsing rules, relevance search and Flint DDL — and implement it once in the Calcite-based engine for reuse across both the OpenSearch and Spark.

Unified SQL Language
├── ANSI SQL Core
├── Search Extension (full-text search, vector search, identifier rules)
└── Secondary Index Extension (Flint DDL)

Phase 1: Analytics engine integration

  • Core DQL — SELECT, subqueries, CTEs, window functions
  • Explain support
  • Full-text search functions

Phase 2: Full language unification

See #5346 (comment) below for the full design and roadmap.

What alternatives have you considered?

  • Keep all engines permanently: Maintenance burden of 4 code paths, inconsistent behavior, no convergence.
  • Strict ANSI SQL only: Breaks existing users who depend on full-text search functions, backtick quoting, and OpenSearch identifier conventions
  • Enable V2 SQL: Since SQL V2 and PPL V3 share the same AST abstraction, it could be routed through the existing CalciteRelNodeVisitor as PPL V3. However, this bypasses Calcite built-in logical optimizations, ANSI SQL features like CTEs etc.

Do you have any additional context?

Activity

  1. added
    enhancement
    on Apr 14, 2026
  2. dai-chen commented on Apr 14, 2026

    @dai-chen
    CollaboratorAuthor

    Unified Query API — SQL Gap Analysis Report (Consolidated)

    Date: 2026-03-30
    Branch: https://github.com/dai-chen/sql-1/tree/poc/gap-analysis-on-formal
    Scope: All SQL IT tests — V2 (org.opensearch.sql.sql.*IT, 50 classes) + Legacy (org.opensearch.sql.legacy.*IT, 39 classes) — 807 queries
    Pipeline: UnifiedQueryPlanner (Calcite native SQL parser) → UnifiedQueryCompiler → PreparedStatement.executeQuery()

    Consolidates the Mar 24 baseline (exception-based failures) and Mar 25 update (added result-mismatch detection).


    Summary

    Metric Count %
    Total Queries 807 100%
    ✅ Success 548 67.9%
    ❌ Failed (Exception) 232 28.7%
    ❌ Failed (Result Mismatch) 27 3.3%
    Total Failed 259 32.1%

    All Failure Categories

    # Category Count Unified SQL? Potential Solution
    0 Table Identifier Compatibility ~750* ✅ Query pre-processor: auto-quote special chars. Or enable ALLOW_HYPHEN_IN_IDENTIFIER + custom lexer rules
    1 Missing Calcite Functions 86 Mixed Register all missing wildcard_query, query operators
    2 EXPR_TIMESTAMP/TIME Type Conversion 22 ✅ Implement EXPR_TIMESTAMP/EXPR_TIME converters in result set reader
    3 Comma-Join / Nested Table Syntax (PartiQL) 26 ❌ No ANSI SQL equivalent — would require custom PartiQL-to-Calcite translation layer
    4 Relevance Function Named Parameters 13 ✅ Extend Calcite SQL parser to support key=value named parameter syntax in function calls
    5 String Literal vs Identifier 2 ❌ N/A — Calcite follows ANSI correctly
    6 Backtick Identifiers 8 ⚠️ Set Quoting.BACK_TICK in SqlParser.Config. Or enable MySQL conformance
    7 GROUP BY Expression Issues 8 ❌ N/A — Calcite enforces ANSI correctly
    8 Wildcard * in nested() 6 ✅ Implement * wildcard expansion inside function arguments during schema resolution
    9 Square Bracket [field] Syntax 17 ✅ Extend Calcite parser to support [field1, field2] array literal syntax in function args
    10 match() Reserved Word 16 ✅ De-reserve MATCH keyword in parser config. Or enable MySQL conformance
    11 Other 28 Mixed See sub-category breakdown
    12 Result Mismatch 27 Mixed See sub-category breakdown
    Total 259

    *Category 0 is not counted in the 259 total — it is silently fixed by the gap analyzer's pre-processing (quoteHyphenatedTableNames). Without this pre-processing, ~750 of 807 queries would fail at PLAN phase.


    Category 0: Table Identifier Compatibility (~750 queries, masked by pre-processing)

    V2/Legacy allows special characters in table identifiers without quoting. Calcite follows ANSI SQL where these require delimited identifiers (double quotes).

    Feature V2 Engine Calcite (ANSI SQL) Impact
    Hyphens (opensearch-sql_test) ✅ Allowed unquoted ❌ Parsed as minus operator ~750 queries
    Dot-prefixed (.kibana) ✅ Allowed unquoted ❌ Parsed as qualifier separator Low (admin indices)
    @ prefix (@timestamp) ✅ Allowed unquoted ❌ Not valid identifier start Low (field names)
    Star wildcards (index*) ✅ Allowed in table names ❌ Not valid in identifiers Low (PPL only)

    The gap analyzer applies a regex-based workaround (quoteHyphenatedTableNames) that wraps hyphenated names after FROM/JOIN in double quotes. This is fragile — it does not cover subqueries, CTEs, or other table reference positions. In production, the unified engine needs a proper identifier
    compatibility layer (either auto-quoting in the query pre-processor or extending the Calcite parser's identifier rules).

    Note: See Identifier documentation for V2's full identifier rules including backtick and double-quote delimited identifiers.

    Category 1: Missing Calcite Functions (86 queries)

    Error: No match found for function signature <name>(...)

    Function Group Count Examples
    Relevance: wildcard_query() / wildcardquery() 22 WHERE wildcard_query(KeywordBody, 'test*')
    Relevance: match_query() / matchquery() 10 WHERE match_query(lastname, 'Bates')
    Relevance: match_phrase() / matchphrase() 10 WHERE match_phrase(phrase, 'quick fox')
    Relevance: match_phrase_prefix() 8 WHERE match_phrase_prefix(Title, 'champagne be')
    Relevance: query() 8 WHERE query('Tags:taste')
    Relevance: multi_match() / multimatch() 3 WHERE multi_match([Title, Body], 'IPA')
    Relevance: matchphrasequery() 2 WHERE matchphrasequery(phrase, 'quick fox')
    Datetime: convert_tz() 17 SELECT convert_tz('2021-05-12','+10:00','+11:00')
    Datetime: DATETIME() 15 SELECT DATETIME('2008-01-01 02:00:00+10:00', '-10:00')
    nested() 1 SELECT nested(message.info)
    percentiles() 2 SELECT percentiles(age, 25.0, 50.0, 75.0, 99.9)
    ISNULL() 1 SELECT ISNULL(lastname)
    Log() (case-sensitive) 1 SELECT Log(MAX(age) + MIN(age))

    Note: Core relevance functions (match, match_phrase, match_bool_prefix, match_phrase_prefix, multi_match, simple_query_string, query_string) support are in progress (#5279)

    Category 2: EXPR_TIMESTAMP/TIME Type Conversion (22 queries)

    Error: class java.lang.String: need to implement EXPR_TIMESTAMP / EXPR_TIME
    OpenSearch returns EXPR_TIMESTAMP/EXPR_TIME typed values that the Calcite pipeline doesn't have a converter for. Affects datetime columns and functions like DATE_FORMAT(). Includes 1 EXPR_TIME query (same root cause).

    Category 3: Comma-Join / Nested Table Syntax (26 queries)

    Error: Table '<name>' not found / no such index [<alias>]
    Legacy syntax FROM t1 e, e.message m treats e.message as a nested field path. Calcite parses it as a table reference. This is an OpenSearch-specific semantic with no ANSI SQL equivalent. Includes 5 queries (previously "Index Not Found") where the table alias (e, tab) passes through to OpenSearch as a literal index name.

    Category 4: Relevance Function Named Parameters (13 queries)

    Error: Column 'slop' not found / Column 'boost' not found / Column 'analyzer' not found / Column 'query' not found
    Relevance functions use key=value named parameter syntax (e.g., match_phrase(phrase, 'quick fox', slop=2)). Calcite doesn't understand this convention and treats slop, boost, analyzer, query, max_expansions as column references.

    Category 5: String Literal vs Identifier (2 queries)

    Error: Column 'Hello' not found in any table
    Calcite follows ANSI SQL: double-quoted strings are identifiers. V2 treats them as string literals (SELECT "Hello").
    Fix: Configure SqlParser.Config quoting behavior, or accept ANSI behavior and document the migration.

    Category 6: Backtick Identifiers (8 queries)

    Error: Lexical error: Encountered "\" (96)**Fix:** ConfigureQuoting.BACK_TICKinSqlParser.Config`.

    Category 7: GROUP BY Expression Issues (8 queries)

    Error: Expression 'lastname' is not being grouped
    Calcite enforces strict GROUP BY validation per ANSI SQL. V2 is more lenient. Includes 1 query where a SELECT alias used in GROUP BY is not resolved.

    Category 8: Wildcard * in nested() (6 queries)

    Error: Unknown field '*'
    nested(message.*) wildcard expansion fails during schema resolution. Distinct from Cat 3 — the nested() function parses fine, but * expansion inside function arguments is unsupported.

    Category 9: Square Bracket [field] Syntax (17 queries)

    Error: Encountered "[" at line 1, column N
    Calcite's parser does not recognize [field1, field2] array literal syntax used by multi_match, query_string, and highlight functions.

    Category 10: match() Reserved Word (16 queries)

    Error: Encountered "match" at line 1, column N
    MATCH is a SQL reserved keyword in Calcite (used for MATCH_RECOGNIZE). OpenSearch uses match() as a full-text search function in WHERE/HAVING clauses.

    Category 11: Other (28 queries)

    Sub Name Count Unified SQL? Potential Solution
    11a SHOW/DESCRIBE Syntax 11 ✅ Fallback to V2/Spark. Or add custom DDL parsing rules
    11b Trailing Semicolons 6 ✅ Pre-processor: strip trailing ; before Calcite parse
    11c Reserved Word as Alias 3 ⚠️ MySQL conformance un-reserves most keywords
    11d CAST BOOLEAN→INT 1 ⚠️ Custom BOOLEAN→INTEGER type coercion rule
    11e Slash in Index Name 1 ❌ N/A — deprecated ES type syntax
    11f Nested Function + AND 1 ❌ No ANSI SQL equivalent — PartiQL nested syntax
    11g Nested Type Access on Array 1 ⚠️ Array-aware field resolution in type system
    11h Quote Escaping (backslash) 1 ⚠️ MySQL conformance enables backslash escaping
    11i TYPEOF Type Restriction 1 ✅ Broaden TYPEOF function signature to accept any type
    11j Runtime Type Cast Error 1 ✅ Handle array fields in result set reader

    Category 12: Result Mismatch (27 queries)

    Both pipelines execute successfully but return different data.

    Sub Name Count Unified SQL? Potential Solution
    12a Extra metadata columns 9 ⚠️ Exclude _id, _index, etc. from SELECT * projection
    12b JOIN row explosion 3 ❌ N/A — V2's implicit LIMIT 200 is non-standard
    12c Column truncation 6 ❌ N/A — V2 stripping ORDER BY columns is non-standard
    12d Numeric precision 1 ❌ N/A — V2 truncating decimals is non-standard
    12e Geo-point format 2 ⚠️ Configure geo-point output format in serializer
    12f LIKE escape 6 ⚠️ MySQL conformance enables implicit \ escape
  3. dai-chen commented on Apr 14, 2026

    @dai-chen
    CollaboratorAuthor

    Unified SQL — Design & Roadmap [WIP]

    1. Gap Analysis Interpretation

    # Category Count Unified SQL [TBD] Potential Solution
    0 Table Identifier Compatibility ~750* ✅ Query pre-processor: auto-quote special chars. Or enable Calcite HYPHENATED_IDENTIFIER support
    1 Missing Calcite Functions 86 Mixed Wire PPLBuiltinOperators into SQL FrameworkConfig.operatorTable(). Add missing wildcard_query, query operators
    2 EXPR_TIMESTAMP/TIME Type Conversion 22 ✅ Implement EXPR_TIMESTAMP/EXPR_TIME converters in result set reader
    3 Comma-Join / Nested Table Syntax (PartiQL) 26 ❌ No ANSI SQL equivalent — would require custom PartiQL-to-Calcite translation layer
    4 Relevance Function Named Parameters 13 ✅ Extend Calcite SQL parser to support key=value named parameter syntax in function calls
    5 String Literal vs Identifier 2 ❌ N/A — Calcite follows ANSI correctly
    6 Backtick Identifiers 8 ⚠️ Set Quoting.BACK_TICK in SqlParser.Config. Or enable MySQL conformance
    7 GROUP BY Expression Issues 8 ❌ N/A — Calcite enforces ANSI correctly
    8 Wildcard * in nested() 6 ✅ Implement * wildcard expansion inside function arguments during schema resolution
    9 Square Bracket [field] Syntax 17 ✅ Extend Calcite parser to support [field1, field2] array literal syntax in function args
    10 match() Reserved Word 16 ✅ De-reserve MATCH keyword via Babel parser
    12 Result Mismatch 27 Mixed See gap analysis report for sub-category breakdown
    Total 259

    * Category 0 is not counted in the 259 total — masked by gap analyzer pre-processing.
    ✅ Must support · ⚠️ Debatable · ❌ Not carrying forward (ANSI SQL is correct)

    2. Roadmap & Full Scope

    Phase 1 covers what's required for the Analytics-engine integration — ANSI SQL with full-text search functions. Phase 2 items need explicit design decisions on how far to diverge from strict ANSI SQL for OpenSearch usability.

    Statement Type SQL V2/Legacy (Plugin) Spark SQL + Flint SQL Unified SQL (Calcite)
    Phase 1
    DQL: SELECT ✅ V2 (simple) + Legacy (JOINs, UNION) ✅ Full Spark SQL 🔄 In progress (this issue)
    Admin: EXPLAIN ✅ REST endpoint (/_explain) ✅ EXPLAIN statement 🔄 In progress (this issue)
    DQL: Subqueries, CTEs, Window ✅ Partial (subquery in FROM/WHERE) ✅ Full (CTEs, window functions) 🔄 In progress (this issue)
    Admin: SHOW/DESCRIBE ✅ SHOW TABLES, DESCRIBE TABLES ✅ SHOW TABLES/DATABASES/COLUMNS SQL V2/Spark fallback
    Phase 2
    DQL: Vector Search ❌ ❌ 📋 Planned (vectorSearch() table function, #5320)
    PreparedStatement ✅ ? params via REST + JDBC driver ❌ 📋 Planned
    Cursor/Pagination ✅ fetch_size + cursor ID (no agg/JOIN) ❌ 📋 Planned
    DDL: Flint Index ❌ ✅ CREATE/DROP/ALTER/REFRESH/VACUUM SKIPPING INDEX, INDEX, MATERIALIZED VIEW 📋 Planned
    DDL: Table ❌ ✅ CREATE/DROP/ALTER TABLE (non-OpenSearch catalogs) Spark fallback
    DML: INSERT/UPDATE/DELETE ❌ ✅ INSERT, UPDATE, DELETE, MERGE Spark fallback

    3. Unified SQL Language [TBD]

    The unified query library defines a single SQL language specification built on ANSI SQL with capability extensions:

    Unified SQL Language
    ├── ANSI SQL Core
    ├── Search Extension
    │   ├── Full-text search (relevance functions, named parameters, multi-field syntax)
    │   ├── Vector search (vectorSearch table function)
    │   └── Data model (identifier rules, nested types, metadata fields, type mappings)
    └── Secondary Index Extension
        └── Flint DDL (skipping index, covering index, materialized view)
    

    The "extension" concept is an internal organizational model — it tracks what the Unified SQL Language adds beyond ANSI SQL. Externally, these are all first-class features of one coherent language specification. Extensions are organized by capability, not by engine, making them portable across Calcite, Spark, DataFusion, or any future execution engine.

    Search Extension

    Category What it adds Examples
    Relevance functions Full-text search as first-class SQL functions match(), match_phrase(), wildcard_query(), query_string(), multi_match(), highlight(), score()
    Named function parameters key=value syntax in function calls match_phrase(field, text, slop=2, boost=1.0)
    Array literal in function args Multi-field specification multi_match([field1, field2], text)
    Vector search Table function for knn queries vectorSearch(table, field, vector, option)
    Identifier rules Index naming conventions Hyphenated names (logs-2024), dot-prefixed (.kibana), backtick quoting

    Secondary Index Extension (Flint DDL)

    Category What it adds Examples
    Skipping index Secondary index for data skipping CREATE/DROP/ALTER/REFRESH/VACUUM/ANALYZE SKIPPING INDEX
    Covering index Secondary index for covering queries CREATE/DROP/ALTER/REFRESH/VACUUM INDEX
    Materialized view Precomputed query results CREATE/DROP/ALTER/REFRESH/VACUUM MATERIALIZED VIEW
    Index management Cross-index operations SHOW FLINT INDEXES, RECOVER INDEX JOB

    4. Implementation Architecture (in Calcite)

    The capability extensions map to Calcite's distinct extension seams. Each seam has a specific role — they should not be conflated:

    Calcite Seam What it controls Extension concerns mapped here
    Custom Parser Grammar (config.fmpp, parserImpls.ftl) New syntax rules Named parameters (key=value), array literals ([field1, field2]), Flint DDL statements, SHOW/DESCRIBE
    Parser Config (SqlParser.Config, Lex) Lexical acceptance Backtick quoting, identifier casing, hyphenated identifier support
    Conformance (SqlConformance) Semantic SQL behavior GROUP BY alias, lenient type coercion, LIMIT syntax
    Operator Table (SqlOperatorTable) Function/operator registration Relevance functions, datetime functions, vectorSearch() table function
    Query Pre-processor (before Calcite) Input normalization Auto-quote special-char identifiers, strip trailing semicolons

    How extensions compose

    Pre-processor (auto-quote identifiers, strip semicolons)
      → Custom Parser Grammar
          (ANSI SQL base + Search syntax + Flint DDL syntax)
      → Parser Config
          (backtick quoting, hyphenated identifiers, casing rules)
      → Conformance
          (ANSI base + semantic accommodations)
      → Chained Operator Table
          (SqlStdOperatorTable + Search functions + datetime)
    
  4. dai-chen commented on May 7, 2026

    @dai-chen
    CollaboratorAuthor

    Function Registration Criteria

    A function is registered in the unified SQL spec only when it has consistent semantics across all execution paths in our stack: OpenSearch SQL V2/legacy, PPL, SparkSQL, and DataFusion (Analytics Engine). Functions must either exist as exact matches in all engines or introduce no conflicting definition in any engine. This ensures the unified language surface remains portable. Functions with engine-specific semantics (e.g., MySQL-only behavior diverging from Spark) should be excluded to avoid creating unification debt.

    Tier 1: Calcite Standard (SqlStdOperatorTable) — Zero Risk

    Already available in Calcite's standard operator table. Enable directly.

    Math

    Function Calcite Operator SparkSQL Match
    ABS(expr) SqlStdOperatorTable.ABS EXACT
    ACOS(expr) SqlStdOperatorTable.ACOS EXACT
    ASIN(expr) SqlStdOperatorTable.ASIN EXACT
    ATAN(expr) SqlStdOperatorTable.ATAN EXACT
    ATAN2(y, x) SqlStdOperatorTable.ATAN2 EXACT
    CEIL(expr) / CEILING(expr) SqlStdOperatorTable.CEIL EXACT (single-arg)
    COS(expr) SqlStdOperatorTable.COS EXACT
    COT(expr) SqlStdOperatorTable.COT EXACT
    DEGREES(expr) SqlStdOperatorTable.DEGREES EXACT
    EXP(expr) SqlStdOperatorTable.EXP EXACT
    FLOOR(expr) SqlStdOperatorTable.FLOOR EXACT (single-arg)
    LN(expr) SqlStdOperatorTable.LN EXACT
    LOG10(expr) SqlStdOperatorTable.LOG10 EXACT
    MOD(expr1, expr2) SqlStdOperatorTable.MOD EXACT
    PI() SqlStdOperatorTable.PI EXACT
    POWER(expr1, expr2) SqlStdOperatorTable.POWER EXACT
    RADIANS(expr) SqlStdOperatorTable.RADIANS EXACT
    RAND([seed]) SqlStdOperatorTable.RAND EXACT
    ROUND(expr, d) SqlStdOperatorTable.ROUND EXACT
    SIGN(expr) SqlStdOperatorTable.SIGN EXACT
    SIN(expr) SqlStdOperatorTable.SIN EXACT
    SQRT(expr) SqlStdOperatorTable.SQRT EXACT
    TAN(expr) SqlStdOperatorTable.TAN EXACT
    TRUNCATE(expr, d) SqlStdOperatorTable.TRUNCATE ⚠️ Calcite has it, Spark does NOT — see notes

    Note on TRUNCATE: Calcite standard table includes it, but SparkSQL has no numeric TRUNCATE. Do NOT register despite Calcite availability — it fails the Spark-alignment criterion.

    String

    Function Calcite Operator SparkSQL Match
    ASCII(str) SqlStdOperatorTable.ASCII EXACT
    LOWER(str) SqlStdOperatorTable.LOWER EXACT
    UPPER(str) SqlStdOperatorTable.UPPER EXACT
    SUBSTRING(str, pos[, len]) SqlStdOperatorTable.SUBSTRING EXACT
    TRIM([LEADING|TRAILING|BOTH] FROM str) SqlStdOperatorTable.TRIM EXACT
    REPLACE(str, search, repl) SqlStdOperatorTable.REPLACE EXACT
    POSITION(sub IN str) SqlStdOperatorTable.POSITION EXACT (covers LOCATE semantics)
    CHAR_LENGTH(str) SqlStdOperatorTable.CHAR_LENGTH EXACT

    Date/Time

    Function Calcite Operator SparkSQL Match
    CURRENT_DATE SqlStdOperatorTable.CURRENT_DATE EXACT
    CURRENT_TIMESTAMP SqlStdOperatorTable.CURRENT_TIMESTAMP EXACT
    CURRENT_TIME SqlStdOperatorTable.CURRENT_TIME EXACT
    YEAR(date) SqlStdOperatorTable.YEAR EXACT
    MONTH(date) SqlStdOperatorTable.MONTH EXACT
    DAYOFMONTH(date) SqlStdOperatorTable.DAYOFMONTH EXACT
    HOUR(ts) SqlStdOperatorTable.HOUR EXACT
    MINUTE(ts) SqlStdOperatorTable.MINUTE EXACT
    SECOND(ts) SqlStdOperatorTable.SECOND EXACT
    DAYOFWEEK(date) SqlStdOperatorTable.DAYOFWEEK EXACT
    DAYOFYEAR(date) SqlStdOperatorTable.DAYOFYEAR EXACT
    QUARTER(date) SqlStdOperatorTable.QUARTER EXACT
    WEEK(date) SqlStdOperatorTable.WEEK EXACT (ISO week only)
    TIMESTAMPADD(unit, n, ts) SqlStdOperatorTable.TIMESTAMP_ADD EXACT
    TIMESTAMPDIFF(unit, a, b) SqlStdOperatorTable.TIMESTAMP_DIFF EXACT

    Conditional

    Function Calcite Operator SparkSQL Match
    CASE WHEN ... THEN ... END SqlStdOperatorTable.CASE EXACT
    COALESCE(expr1, expr2, ...) SqlStdOperatorTable.COALESCE EXACT
    NULLIF(expr1, expr2) SqlStdOperatorTable.NULLIF EXACT

    Aggregate

    Function Calcite Operator SparkSQL Match
    AVG(expr) SqlStdOperatorTable.AVG EXACT
    COUNT(expr) SqlStdOperatorTable.COUNT EXACT
    MAX(expr) SqlStdOperatorTable.MAX EXACT
    MIN(expr) SqlStdOperatorTable.MIN EXACT
    SUM(expr) SqlStdOperatorTable.SUM EXACT
    VAR_POP(expr) SqlStdOperatorTable.VAR_POP EXACT
    VAR_SAMP(expr) SqlStdOperatorTable.VAR_SAMP EXACT
    STDDEV_POP(expr) SqlStdOperatorTable.STDDEV_POP EXACT
    STDDEV_SAMP(expr) SqlStdOperatorTable.STDDEV_SAMP EXACT

    Tier 1 Total: ~41 functions


    Tier 2: Calcite Library (SqlLibrary.SPARK) — Low Risk

    Require enabling the SPARK library tag. All have exact SparkSQL semantics.

    Function Calcite Library Operator SparkSQL Match
    POW(x, y) SqlLibraryOperators.POW (SPARK) EXACT (alias for POWER)
    LEFT(str, n) SqlLibraryOperators.LEFT (SPARK) EXACT
    RIGHT(str, n) SqlLibraryOperators.RIGHT (SPARK) EXACT
    CONCAT_WS(sep, str1, ...) SqlLibraryOperators.CONCAT_WS_SPARK (SPARK) EXACT
    REVERSE(str) SqlLibraryOperators.REVERSE_SPARK (SPARK) EXACT
    LTRIM(str) SqlLibraryOperators.LTRIM (SPARK) EXACT
    RTRIM(str) SqlLibraryOperators.RTRIM (SPARK) EXACT
    CONCAT(str1, str2, ...) SqlLibraryOperators.CONCAT_FUNCTION (MYSQL, BIG_QUERY) EXACT
    LENGTH(str) SqlLibraryOperators.LENGTH (SPARK) EXACT (alias for CHAR_LENGTH)
    IFNULL(x, y) SqlLibraryOperators.IFNULL (SPARK) EXACT
    NVL(x, y) SqlLibraryOperators.NVL (SPARK) EXACT
    DATE_ADD(date, numDays) SqlLibraryOperators.DATE_ADD_SPARK (SPARK, HIVE) EXACT (integer days only)
    DATE_SUB(date, numDays) SqlLibraryOperators.DATE_SUB_SPARK (SPARK, HIVE) EXACT (integer days only)
    REGEXP_REPLACE(str, pat, repl) SqlLibraryOperators.REGEXP_REPLACE_3 (POSTGRESQL, BIG_QUERY) EXACT (Spark-compatible)

    Tier 2 Total: ~14 functions

    Implementation

    SqlLibraryOperatorTableFactory.INSTANCE.getOperatorTable(
        EnumSet.of(SqlLibrary.SPARK))

    Important: Register ONLY SqlLibrary.SPARK. Do NOT bulk-register MYSQL/POSTGRESQL/BIG_QUERY — they pull in conflicting definitions.

    For functions tagged under other libraries but Spark-compatible (e.g., REGEXP_REPLACE_3), cherry-pick individually rather than enabling the entire library.


    Tier 3: Custom Registration (Spark-Aligned) — Moderate Effort

    Not in Calcite's standard/library tables but have exact SparkSQL equivalents. Implement as custom SqlFunction with Spark-identical signatures.

    Function Signature Notes
    IF(cond, expr1, expr2) (BOOLEAN, ANY, ANY) → ANY Spark built-in; standard SQL uses CASE
    ISNULL(expr) (ANY) → BOOLEAN Spark predicate function
    LOG(x) / LOG(base, x) (NUMERIC[, NUMERIC]) → DOUBLE Use Calcite's LOG_MYSQL variant (accepts 1 or 2 args)
    DATE_FORMAT(ts, fmt) (TIMESTAMP, VARCHAR) → VARCHAR Spark exact match
    FROM_UNIXTIME(n[, fmt]) (BIGINT[, VARCHAR]) → VARCHAR Spark exact match
    UNIX_TIMESTAMP([ts[, fmt]]) ([TIMESTAMP[, VARCHAR]]) → BIGINT Spark exact match
    DATEDIFF(end, start) (DATE, DATE) → INT 2-arg form (Spark). Do NOT use Calcite's 3-arg MSSQL form
    NOW() () → TIMESTAMP Spark exact match (alias for CURRENT_TIMESTAMP)

    Tier 3 Total: ~8 functions


    Tier 4: DO NOT REGISTER — Unification Risk

    These functions either don't exist in SparkSQL, have different semantics, or are MySQL/OpenSearch-specific.

    MySQL-isms (different or absent in Spark)

    Function Reason
    TRUNCATE(x, d) Spark has no numeric TRUNCATE
    STRCMP(a, b) Not in Spark
    ADDDATE(date, ...) MySQL alias — use DATE_ADD
    SUBDATE(date, ...) MySQL alias — use DATE_SUB
    DATE(expr) MySQL cast — Spark uses to_date()
    TIME(expr) MySQL cast — no Spark equivalent
    TIMESTAMP(expr) MySQL cast — Spark uses to_timestamp()
    TO_DAYS(date) MySQL-specific
    MAKEDATE(year, doy) Different signature from Spark's make_date(y,m,d)
    MAKETIME(h, m, s) Spark 4.1+ only, not stable
    CURDATE(), CURTIME() MySQL aliases — use CURRENT_DATE/CURRENT_TIME
    NOW(), SYSDATE() NOW is Tier 3 (Spark has it); SYSDATE is MySQL-specific
    DAYNAME(x), MONTHNAME(x) Different return format (full vs abbreviated)
    WEEK(date, mode) Mode parameter not in Spark
    STR_TO_DATE, GET_FORMAT, CONVERT_TZ MySQL-specific
    FROM_DAYS, TO_SECONDS, YEARWEEK MySQL-specific
    SEC_TO_TIME, TIME_TO_SEC MySQL-specific
    UTC_DATE, UTC_TIME, UTC_TIMESTAMP No Spark equivalent
    PERIOD_ADD, PERIOD_DIFF MySQL-specific
    TIMEDIFF, ADDTIME, SUBTIME MySQL-specific

    BigQuery-specific (no Spark equivalent)

    Function Reason
    SAFE_DIVIDE BigQuery-only
    REGEXP_CONTAINS BigQuery-only — Spark uses RLIKE

    Java Math / Non-standard

    Function Reason
    SINH, COSH, EXPM1 Java Math functions, not SQL standard
    RINT, SIGNUM Java Math functions
    E() Spark has it but it's trivial; use literal 2.718...
    STD(x) MySQL alias for STDDEV_POP
    CONV(x, from, to) Utility function, not standard SQL
    CRC32(s) Hash function, not standard SQL

    Operator function-call forms

    Function Reason
    ADD(a, b), SUBTRACT(a, b), MULTIPLY(a, b), DIVIDE(a, b), MODULUS(a, b) Use operators +, -, *, /, MOD

    OpenSearch-specific

    Function Reason
    NESTED, REVERSE_NESTED OpenSearch document model
    GEO_INTERSECTS, GEO_BOUNDING_BOX OpenSearch geo DSL
    TERMS, HIGHLIGHT, SCORE OpenSearch search API
    TYPEOF, TYPE, FIELD Type introspection, non-standard
    PERCENTILE, PERCENTILE_APPROX Semantics differ from Spark's percentile_approx
    All relevance functions (MATCH, MATCH_PHRASE, etc.) Already handled separately via UnifiedFunctionSpec.RELEVANCE
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    SQLenhancement

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions