Skip to main content

sqlglot-flink

CI PyPI OpenSSF Scorecard

sqlglot-flink, a Flink SQL dialect for sqlglot, packaged as a sqlglot dialect plugin.

With it, sqlglot can turn SQL written for another engine into SQL Flink runs, turn Flink SQL into SQL for other engines, and parse and regenerate Flink SQL, including its streaming syntax, without breaking it.

import sqlglot

sqlglot.transpile(
    "SELECT DATE_TRUNC('hour', ts), STRPOS(s, 'x'), 7 / 2, s ILIKE 'a%' FROM t",
    read="postgres",
    write="flink",
)
# ["SELECT FLOOR(ts TO HOUR), POSITION('x' IN s), 7 / 2, LOWER(s) LIKE LOWER('a%') FROM t"]

sqlglot.transpile("SELECT FLOOR(ts TO DAY), LOCATE('b', s) FROM t", read="flink", write="duckdb")
# ["SELECT DATE_TRUNC('DAY', ts), STRPOS(s, 'b') FROM t"]

Install

pip install sqlglot-flink

Installing the package registers the dialect with sqlglot under the name flink; there is nothing to import. You can also use the class directly:

from sqlglot_flink import Flink

Requires Python 3.10+ and sqlglot 30 or later.

What it handles

The dialect builds on sqlglot's Spark dialect. Flink's built-in functions copy much of the Hive library (DATE_FORMAT, FROM_UNIXTIME, UNIX_TIMESTAMP, REGEXP_EXTRACT, STR_TO_MAP, backtick identifiers), which Hive and Spark share, and Spark adds what Flink also has: TRY_CAST, TO_TIMESTAMP(s, fmt), TIMESTAMPADD/TIMESTAMPDIFF(unit, ...), the TIMESTAMP_LTZ type and /*+ ... */ query hints. Where Flink follows Apache Calcite instead, the dialect overrides Spark.

Flink SQL that round-trips:

  • backtick identifiers, case-sensitive; reserved words such as value and raw stay quoted; strings in single quotes with '', no backslash escapes;
  • types STRING, BYTES, TIMESTAMP(p), TIMESTAMP_LTZ(p) (and TIMESTAMP(p) WITH LOCAL TIME ZONE), ARRAY<T>, MAP<K, V>, ROW<a INT, b STRING>, MULTISET<T>, ARRAY[...], MAP[...], ROW(...);
  • window table-valued functions TUMBLE, HOP, CUMULATE and SESSION over TABLE t [PARTITION BY ...] and DESCRIPTOR(ts), with positional or named (DATA => ...) arguments;
  • temporal joins (FOR SYSTEM_TIME AS OF o.order_time), OVER windows with RANGE BETWEEN INTERVAL ... PRECEDING, named WINDOW clauses;
  • dynamic table options t /*+ OPTIONS('k'='v') */ and join hints SELECT /*+ BROADCAST(t) */;
  • CREATE TABLE with computed columns, METADATA [FROM 'key'] [VIRTUAL] columns, WATERMARK FOR ts AS ts - INTERVAL '5' SECOND, PRIMARY KEY (...) NOT ENFORCED, PARTITIONED BY and WITH (...);
  • MATCH_RECOGNIZE, CROSS JOIN UNNEST, CURRENT_WATERMARK, LISTAGG, COLLECT, JSON_VALUE(... RETURNING ...), JSON_OBJECT(k VALUE v).

SQL from other dialects, translated to what Flink spells or means differently:

Other dialects Flink SQL generated
DATE_TRUNC('day', ts) FLOOR(ts TO DAY)
DATE_DIFF('day', a, b), DATEDIFF(b, a) TIMESTAMPDIFF(DAY, a, b)
DATE_ADD('hour', 3, ts), DATE_ADD(d, 1) TIMESTAMPADD(HOUR, 3, ts), TIMESTAMPADD(DAY, 1, d)
LENGTH(s) CHAR_LENGTH(s)
STRPOS(s, x), INSTR(s, x) POSITION(x IN s)
s ILIKE p LOWER(s) LIKE LOWER(p) (Flink has no ILIKE)
s ~ p, s RLIKE p REGEXP(s, p)
STRING_AGG(x, ',') LISTAGG(x)
x ->> 'a', GET_JSON_OBJECT(x, '$.a') JSON_VALUE(x, '$.a')
LATERAL VIEW EXPLODE(arr) t AS x CROSS JOIN UNNEST(arr) AS t(x)
TO_TIMESTAMP(epoch) (DuckDB) TO_TIMESTAMP_LTZ(epoch, 0)
STRFTIME, TO_CHAR patterns Java patterns: DATE_FORMAT(ts, 'yyyy-MM-dd')
VARCHAR, TEXT, BYTEA, unbounded BINARY STRING, BYTES
TIMESTAMPTZ TIMESTAMP_LTZ
LOG(x) (Postgres, base 10) LOG10(x)
QUALIFY ... a filtered subquery

These are tested against a live Flink, by value, not only by acceptance:

  • Integer division truncates. 7 / 2 is 3 and -7 / 2 is -3, as in Postgres and Trino. DuckDB's and Spark's / divides as doubles, so their 7 / 2 becomes CAST(7 AS DOUBLE) / 2; 7 // 2 and 7 DIV 2 become CAST(7 / 2 AS BIGINT).
  • Division by zero fails the job. Spark returns NULL, so a Spark divisor is wrapped in NULLIF(d, 0).
  • String positions are 1-based and 0 means absent, like the standard, so POSITION, LOCATE and SUBSTRING keep their arguments.
  • CONCAT returns NULL if any argument is NULL (CONCAT_WS skips NULLs). Postgres skips them, so its arguments get COALESCE(x, '').
  • NULLs sort first in ascending order. Postgres sorts them last, so its ORDER BY gets an explicit NULLS LAST.
  • Arrays are 1-based; Spark's arr[0] becomes arr[1].
  • LOG(x) with one argument is the natural log; it reads as LN(x).
  • REGEXP_EXTRACT(s, re) without an index returns the whole match, where Hive and Spark return group 1, so Spark's call gets an explicit 1.
  • CHAR, VARCHAR, BINARY and VARBINARY without a length mean length 1. Flink SQL's CAST(x AS VARCHAR) is written as VARCHAR(1); the unbounded VARCHAR of other dialects becomes STRING.
  • STR_TO_MAP(s) splits on , and = (Hive uses :).

How it is tested

tests/corpus.py is a set of queries over deterministic tables (views over VALUES and a bounded datagen table) that the tests create in each session:

  • 131 Flink queries that must round-trip, 116 of them with expected rows;
  • 81 queries from Postgres, Spark, DuckDB, Trino and MySQL that must become the expected Flink SQL, all with expected rows.

The unit tests check the generated SQL text. The live tests send every corpus query, and every generated query, to a real Flink SQL Gateway: batch queries run in batch mode and their rows are compared; queries Flink only accepts in streaming mode (session windows, temporal joins, OVER ... RANGE with an interval, CURRENT_WATERMARK) are planned with EXPLAIN in a streaming session; DDL runs in a fresh session. All 212 pass on Flink 1.20.5 and 2.3.0, and CI runs them against both.

FLINK_VERSION=2.3.0 docker compose -f tests/docker-compose.yml up -d
FLINK_GATEWAY_URL=http://127.0.0.1:8083 pytest
docker compose -f tests/docker-compose.yml down

scripts/check_versions.sh 1.20.5 2.3.0 runs the same check against a fresh cluster of each version; scripts/live_check.py prints every mismatch.

Limitations

  • TIMESTAMPDIFF counts whole units. DATE_DIFF('day', ...) in DuckDB or Trino counts day boundaries crossed, so for timestamps less than a day apart across midnight they differ (1 against 0). Dates give the same answer.
  • Spark's TIMESTAMP is zoned, so it becomes TIMESTAMP_LTZ, and results carry the session time zone.
  • Not translated: BOOL_AND/BOOL_OR (Flink has none), regular-expression SPLIT (Flink's SPLIT takes a literal delimiter), LISTAGG ... ORDER BY, STATEMENT SET, EXECUTE, and Flink-only DDL such as CREATE CATALOG or CREATE FUNCTION ... USING JAR, which parse as sqlglot commands at best.
  • Flink-only functions pass through as written (SPLIT_INDEX, CURRENT_WATERMARK, PROCTIME, DESCRIPTOR, window TVFs); they are not rewritten for other dialects.
  • INTERVAL '10' MINUTES is written as INTERVAL '10' MINUTE, and IFNULL as COALESCE.

Contributing

Bug reports and pull requests are welcome: see CONTRIBUTING.md for how to report a problem, run the tests and send a change. Report security problems privately, as described in SECURITY.md. Changes are listed in CHANGELOG.md.

License

Apache License 2.0. See LICENSE.

Apache Flink, Flink and the Flink logo are trademarks of the Apache Software Foundation. This project is not affiliated with or endorsed by the Apache Software Foundation.

Metadata

Release files for sqlglot-flink 0.2.0

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for sqlglot-flink 0.2.0
File Size Uploaded Provenance Actions
sqlglot_flink-0.2.0.tar.gz 37.7 kB With provenance Details for sqlglot_flink-0.2.0.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for sqlglot-flink 0.2.0
File Interpreter ABI Platform Actions
sqlglot_flink-0.2.0-py3-none-any.whl Python 3 none any Details for sqlglot_flink-0.2.0-py3-none-any.whl

Total release size: 57.1 kB

Security for sqlglot-flink 0.2.0

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

Full provenance

Both files in this release have been uploaded with provenance metadata.

Select from 2 files

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Release history Release notifications | RSS feed

This release

0.2.0 This release

2 release files Full provenance

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page