sqlglot-flink 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,12 @@
1
+ """sqlglot-flink, a Flink SQL dialect for sqlglot.
2
+
3
+ Installing the package registers the dialect under the name ``flink``::
4
+
5
+ import sqlglot
6
+ sqlglot.transpile("SELECT DATE_TRUNC('day', ts) FROM t", read="postgres", write="flink")
7
+ """
8
+
9
+ from sqlglot_flink.dialect import Flink
10
+
11
+ __all__ = ["Flink"]
12
+ __version__ = "0.1.0"
@@ -0,0 +1,815 @@
1
+ """A sqlglot dialect for Flink SQL."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from sqlglot import exp, generator, parser, transforms
6
+ from sqlglot.dialects.dialect import (
7
+ NormalizationStrategy,
8
+ explode_to_unnest_sql,
9
+ no_ilike_sql,
10
+ rename_func,
11
+ )
12
+ from sqlglot.dialects.spark import Spark
13
+ from sqlglot.generators.spark import SparkGenerator
14
+ from sqlglot.helper import seq_get
15
+ from sqlglot.parsers.spark import SparkParser
16
+ from sqlglot.tokens import TokenType
17
+
18
+ # Why Spark and not Hive: both carry the Hive function library that Flink's
19
+ # built-in functions copy (DATE_FORMAT, FROM_UNIXTIME, UNIX_TIMESTAMP,
20
+ # REGEXP_EXTRACT, STR_TO_MAP, backtick identifiers), but only Spark's dialect
21
+ # also has the parts Flink shares with Spark 3: TRY_CAST, TO_TIMESTAMP(s, fmt),
22
+ # TIMESTAMPADD/TIMESTAMPDIFF(unit, ...), the TIMESTAMP_LTZ type name and
23
+ # /*+ ... */ query hints. What Flink takes from Calcite instead (single-quoted
24
+ # strings with '' escapes, integer division, CHAR_LENGTH, POSITION, FLOOR(ts TO
25
+ # unit), INTERVAL '5' SECOND, UNNEST, standard SUBSTRING) is overridden here.
26
+
27
+ # The default pattern of TO_TIMESTAMP(s) and UNIX_TIMESTAMP(s) in Flink.
28
+ DEFAULT_TIME_FORMAT = "yyyy-MM-dd HH:mm:ss"
29
+
30
+ # Units Flink's TIMESTAMPADD, TIMESTAMPDIFF, FLOOR(... TO unit) and EXTRACT accept.
31
+ _UNITS = {
32
+ "MILLENNIUM",
33
+ "CENTURY",
34
+ "DECADE",
35
+ "YEAR",
36
+ "QUARTER",
37
+ "MONTH",
38
+ "WEEK",
39
+ "DAY",
40
+ "HOUR",
41
+ "MINUTE",
42
+ "SECOND",
43
+ "MILLISECOND",
44
+ "MICROSECOND",
45
+ "NANOSECOND",
46
+ }
47
+
48
+
49
+ def _unit(expression: exp.Expr, default: str = "DAY") -> exp.Var:
50
+ """A date part as Flink writes it: an upper-case keyword such as DAY."""
51
+ unit = expression.args.get("unit")
52
+ name = (unit.name if unit is not None else default).upper() or default
53
+ name = {"DAYS": "DAY", "HOURS": "HOUR", "MINUTES": "MINUTE", "SECONDS": "SECOND"}.get(
54
+ name, name
55
+ )
56
+ return exp.var(name)
57
+
58
+
59
+ def _is_default_format(self: FlinkGenerator, expression: exp.Expr) -> bool:
60
+ """Whether a time format is Flink's default, 'yyyy-MM-dd HH:mm:ss'."""
61
+ if expression.args.get("format") is None:
62
+ return True
63
+ return self.format_time(expression) == f"'{DEFAULT_TIME_FORMAT}'"
64
+
65
+
66
+ def _build_to_timestamp(args: list, dialect: Flink) -> exp.Expr:
67
+ # TO_TIMESTAMP(s[, format]) parses s with a Java DateTimeFormatter pattern,
68
+ # 'yyyy-MM-dd HH:mm:ss' by default, and returns TIMESTAMP(3).
69
+ fmt = seq_get(args, 1) or exp.Literal.string(DEFAULT_TIME_FORMAT)
70
+ return exp.StrToTime(this=seq_get(args, 0), format=dialect.format_time(fmt))
71
+
72
+
73
+ def _build_to_timestamp_ltz(args: list) -> exp.Expr:
74
+ # TO_TIMESTAMP_LTZ(numeric, precision) reads epoch seconds (precision 0) or
75
+ # milliseconds (precision 3). Other forms are kept as written.
76
+ precision = seq_get(args, 1)
77
+ if len(args) == 2 and isinstance(precision, exp.Literal) and precision.name in ("0", "3"):
78
+ scale = exp.UnixToTime.SECONDS if precision.name == "0" else exp.UnixToTime.MILLIS
79
+ return exp.UnixToTime(this=args[0], scale=scale)
80
+ if len(args) == 1:
81
+ return exp.UnixToTime(this=args[0], scale=exp.UnixToTime.MILLIS)
82
+ return exp.Anonymous(this="TO_TIMESTAMP_LTZ", expressions=args)
83
+
84
+
85
+ def _build_locate(args: list) -> exp.StrPosition:
86
+ # LOCATE(sub, s[, start]) is 1-based and returns 0 when sub is absent.
87
+ return exp.StrPosition(
88
+ this=seq_get(args, 1), substr=seq_get(args, 0), position=seq_get(args, 2)
89
+ )
90
+
91
+
92
+ def _build_timestampdiff(args: list) -> exp.Expr:
93
+ # TIMESTAMPDIFF(unit, start, end) = end - start, truncated to whole units.
94
+ if len(args) != 3:
95
+ return exp.Anonymous(this="TIMESTAMPDIFF", expressions=args)
96
+ return exp.TimestampDiff(this=args[2], expression=args[1], unit=exp.var(args[0].name.upper()))
97
+
98
+
99
+ def _build_timestampadd(args: list) -> exp.Expr:
100
+ if len(args) != 3:
101
+ return exp.Anonymous(this="TIMESTAMPADD", expressions=args)
102
+ return exp.TimestampAdd(this=args[2], expression=args[1], unit=exp.var(args[0].name.upper()))
103
+
104
+
105
+ def _build_json_query(args: list, dialect: Flink) -> exp.Expr:
106
+ if len(args) == 2:
107
+ return exp.JSONExtract(this=args[0], expression=dialect.to_json_path(args[1]))
108
+ return exp.Anonymous(this="JSON_QUERY", expressions=args)
109
+
110
+
111
+ # Generator helpers -----------------------------------------------------------
112
+
113
+
114
+ def _timestampadd_sql(
115
+ self: FlinkGenerator,
116
+ expression: exp.TimestampAdd | exp.DateAdd | exp.TsOrDsAdd | exp.DatetimeAdd,
117
+ ) -> str:
118
+ return self.func("TIMESTAMPADD", _unit(expression), expression.expression, expression.this)
119
+
120
+
121
+ def _timestampsub_sql(
122
+ self: FlinkGenerator, expression: exp.TimestampSub | exp.DateSub | exp.DatetimeSub
123
+ ) -> str:
124
+ amount = expression.expression
125
+ negated = amount.this if isinstance(amount, exp.Neg) else exp.Neg(this=amount.copy())
126
+ return self.func("TIMESTAMPADD", _unit(expression), negated, expression.this)
127
+
128
+
129
+ def _timestampdiff_sql(
130
+ self: FlinkGenerator, expression: exp.TimestampDiff | exp.DateDiff | exp.DatetimeDiff
131
+ ) -> str:
132
+ return self.func("TIMESTAMPDIFF", _unit(expression), expression.expression, expression.this)
133
+
134
+
135
+ def _trunc_sql(self: FlinkGenerator, expression: exp.TimestampTrunc | exp.DateTrunc) -> str:
136
+ # Flink has no DATE_TRUNC; FLOOR(ts TO unit) rounds down to the unit.
137
+ unit = _unit(expression)
138
+ if unit.name not in _UNITS:
139
+ self.unsupported(f"Flink cannot truncate to {unit.name}")
140
+ return f"FLOOR({self.sql(expression, 'this')} TO {unit.name})"
141
+
142
+
143
+ def _str_to_time_sql(self: FlinkGenerator, expression: exp.StrToTime) -> str:
144
+ if _is_default_format(self, expression):
145
+ return self.func("TO_TIMESTAMP", expression.this)
146
+ return self.func("TO_TIMESTAMP", expression.this, self.format_time(expression))
147
+
148
+
149
+ def _str_to_date_sql(self: FlinkGenerator, expression: exp.StrToDate) -> str:
150
+ fmt = self.format_time(expression)
151
+ if fmt in (None, "'yyyy-MM-dd'"):
152
+ return self.func("TO_DATE", expression.this)
153
+ return self.func("TO_DATE", expression.this, fmt)
154
+
155
+
156
+ def _ts_or_ds_to_date_sql(self: FlinkGenerator, expression: exp.TsOrDsToDate) -> str:
157
+ fmt = expression.args.get("format")
158
+ if fmt is not None and self.format_time(expression) not in ("'yyyy-MM-dd'",):
159
+ return self.func("TO_DATE", expression.this, self.format_time(expression))
160
+ if expression.this.is_type(exp.DType.DATE):
161
+ return self.sql(expression, "this")
162
+ return self.sql(exp.cast(expression.this, exp.DType.DATE))
163
+
164
+
165
+ def _str_to_unix_sql(self: FlinkGenerator, expression: exp.StrToUnix) -> str:
166
+ if _is_default_format(self, expression):
167
+ return self.func("UNIX_TIMESTAMP", expression.this)
168
+ return self.func("UNIX_TIMESTAMP", expression.this, self.format_time(expression))
169
+
170
+
171
+ def _unix_to_str_sql(self: FlinkGenerator, expression: exp.UnixToStr) -> str:
172
+ if _is_default_format(self, expression):
173
+ return self.func("FROM_UNIXTIME", expression.this)
174
+ return self.func("FROM_UNIXTIME", expression.this, self.format_time(expression))
175
+
176
+
177
+ def _unix_to_time_sql(self: FlinkGenerator, expression: exp.UnixToTime) -> str:
178
+ scale = expression.args.get("scale")
179
+ if scale is None or scale == exp.UnixToTime.SECONDS or _int(scale) == 0:
180
+ precision = 0
181
+ elif scale == exp.UnixToTime.MILLIS or _int(scale) == 3:
182
+ precision = 3
183
+ else:
184
+ self.unsupported("Flink's TO_TIMESTAMP_LTZ reads seconds or milliseconds")
185
+ precision = 0
186
+ return self.func("TO_TIMESTAMP_LTZ", expression.this, exp.Literal.number(precision))
187
+
188
+
189
+ def _int(value: exp.Expr | None) -> int | None:
190
+ if isinstance(value, exp.Literal) and value.is_int:
191
+ return int(value.name)
192
+ return None
193
+
194
+
195
+ def _str_position_sql(self: FlinkGenerator, expression: exp.StrPosition) -> str:
196
+ # POSITION(sub IN s) and LOCATE(sub, s, start) are 1-based, 0 when absent.
197
+ substr = expression.args.get("substr")
198
+ position = expression.args.get("position")
199
+ if expression.args.get("occurrence"):
200
+ self.unsupported("Flink's POSITION has no occurrence argument")
201
+ if position is not None:
202
+ return self.func("LOCATE", substr, expression.this, position)
203
+ return f"POSITION({self.sql(substr)} IN {self.sql(expression, 'this')})"
204
+
205
+
206
+ def _map_sql(self: FlinkGenerator, expression: exp.VarMap | exp.Map) -> str:
207
+ keys, values = expression.args.get("keys"), expression.args.get("values")
208
+ if not isinstance(keys, exp.Array) or not isinstance(values, exp.Array):
209
+ if keys is not None:
210
+ self.unsupported("Flink cannot build a map from array columns")
211
+ return self.func("MAP", keys, values)
212
+ pairs = [
213
+ self.sql(e) for pair in zip(keys.expressions, values.expressions, strict=True) for e in pair
214
+ ]
215
+ return f"MAP[{', '.join(pairs)}]"
216
+
217
+
218
+ def _int_div_sql(self: FlinkGenerator, expression: exp.IntDiv) -> str:
219
+ # Integer division that truncates toward zero, like Flink's own INT / INT.
220
+ div = exp.Div(this=expression.this.copy(), expression=expression.expression.copy(), typed=True)
221
+ return self.sql(exp.cast(div, exp.DType.BIGINT))
222
+
223
+
224
+ def _array_size_sql(self: FlinkGenerator, expression: exp.ArraySize) -> str:
225
+ return self.func("CARDINALITY", expression.this)
226
+
227
+
228
+ def _group_concat_sql(self: FlinkGenerator, expression: exp.GroupConcat) -> str:
229
+ this = expression.this
230
+ if isinstance(this, exp.Order):
231
+ self.unsupported("Flink's LISTAGG has no ORDER BY")
232
+ this = this.this
233
+ separator = expression.args.get("separator")
234
+ # LISTAGG's separator defaults to ','.
235
+ if isinstance(separator, exp.Literal) and separator.name == ",":
236
+ separator = None
237
+ return self.func("LISTAGG", this, separator)
238
+
239
+
240
+ def _json_value_sql(self: FlinkGenerator, expression: exp.JSONExtractScalar) -> str:
241
+ return self.func("JSON_VALUE", expression.this, expression.expression)
242
+
243
+
244
+ def _json_query_sql(self: FlinkGenerator, expression: exp.JSONExtract) -> str:
245
+ return self.func("JSON_QUERY", expression.this, expression.expression)
246
+
247
+
248
+ def _qualify_keeping_order(expression: exp.Expr) -> exp.Expr:
249
+ """Rewrite QUALIFY into a filtered subquery, keeping ORDER BY on the outside.
250
+
251
+ sqlglot's eliminate_qualify leaves ORDER BY in the subquery, where it does
252
+ not order the result. When the ordering only names output columns, it is
253
+ moved to the outer query instead.
254
+ """
255
+ if not isinstance(expression, exp.Select) or not expression.args.get("qualify"):
256
+ return expression
257
+ order = expression.args.get("order")
258
+ names = {s.alias_or_name for s in expression.selects}
259
+ movable = order is not None and all(
260
+ not column.table and column.name in names for column in order.find_all(exp.Column)
261
+ )
262
+ if movable:
263
+ expression.set("order", None)
264
+ result = transforms.eliminate_qualify(expression)
265
+ if movable:
266
+ result.set("order", order)
267
+ return result
268
+
269
+
270
+ _LENGTH_ONE_TYPES = {exp.DType.CHAR, exp.DType.VARCHAR, exp.DType.BINARY, exp.DType.VARBINARY}
271
+
272
+
273
+ def _typed_literal(cast: exp.Cast) -> exp.Cast:
274
+ cast.meta["typed_literal"] = True
275
+ return cast
276
+
277
+
278
+ class FlinkParser(SparkParser):
279
+ # LISTAGG's separator defaults to ','.
280
+ STRING_AGG_DEFAULT_SEPARATOR = ","
281
+ LOG_DEFAULTS_TO_LN = True
282
+ STRICT_CAST = True
283
+
284
+ FUNCTIONS = {
285
+ **SparkParser.FUNCTIONS,
286
+ "CHAR_LENGTH": exp.Length.from_arg_list,
287
+ # Hive's YEAR(x) and friends read x as a date string; Flink's take a
288
+ # DATE or TIMESTAMP, so no TO_DATE is wrapped around the argument.
289
+ "YEAR": exp.Year.from_arg_list,
290
+ "QUARTER": exp.Quarter.from_arg_list,
291
+ "MONTH": exp.Month.from_arg_list,
292
+ "WEEK": exp.Week.from_arg_list,
293
+ "DAY": exp.Day.from_arg_list,
294
+ "DAYOFMONTH": exp.DayOfMonth.from_arg_list,
295
+ "DAYOFWEEK": exp.DayOfWeek.from_arg_list,
296
+ "DAYOFYEAR": exp.DayOfYear.from_arg_list,
297
+ "HOUR": exp.Hour.from_arg_list,
298
+ "MINUTE": exp.Minute.from_arg_list,
299
+ "SECOND": exp.Second.from_arg_list,
300
+ "CHARACTER_LENGTH": exp.Length.from_arg_list,
301
+ "CARDINALITY": exp.ArraySize.from_arg_list,
302
+ "INSTR": lambda args: exp.StrPosition(this=seq_get(args, 0), substr=seq_get(args, 1)),
303
+ "JSON_QUERY": _build_json_query,
304
+ "STR_TO_MAP": lambda args: exp.StrToMap(
305
+ this=seq_get(args, 0),
306
+ pair_delim=seq_get(args, 1) or exp.Literal.string(","),
307
+ key_value_delim=seq_get(args, 2) or exp.Literal.string("="),
308
+ ),
309
+ "TO_BASE64": exp.ToBase64.from_arg_list,
310
+ "FROM_BASE64": exp.FromBase64.from_arg_list,
311
+ "LOCATE": _build_locate,
312
+ "REGEXP": exp.RegexpLike.from_arg_list,
313
+ "TIMESTAMPADD": _build_timestampadd,
314
+ "TIMESTAMPDIFF": _build_timestampdiff,
315
+ "TO_TIMESTAMP": _build_to_timestamp,
316
+ # TO_DATE(s[, format]) parses a string, 'yyyy-MM-dd' by default.
317
+ "TO_DATE": lambda args, dialect: exp.StrToDate(
318
+ this=seq_get(args, 0),
319
+ format=dialect.format_time(seq_get(args, 1) or exp.Literal.string("yyyy-MM-dd")),
320
+ ),
321
+ "TO_TIMESTAMP_LTZ": _build_to_timestamp_ltz,
322
+ }
323
+ # Spark-only spellings Flink does not have are left as plain functions, so
324
+ # that a Flink query that happens to call a UDF by that name survives.
325
+ for _name in ("DATEDIFF", "DATE_DIFF", "DATE_ADD", "DATEADD", "SIZE", "DATE_TRUNC", "TRUNC"):
326
+ FUNCTIONS.pop(_name, None)
327
+ del _name
328
+
329
+ LAMBDAS = {
330
+ **SparkParser.LAMBDAS,
331
+ # DATA => TABLE t, as in TUMBLE(DATA => TABLE t, TIMECOL => ...).
332
+ TokenType.FARROW: lambda self, expressions: self.expression(
333
+ exp.Kwarg(
334
+ this=exp.var(expressions[0].name),
335
+ expression=self._parse_table_function_arg()
336
+ or self._parse_disjunction()
337
+ or self._parse_select(),
338
+ )
339
+ ),
340
+ }
341
+
342
+ # Spark reads EXTRACT(DOW FROM x) as DAYOFWEEK(x); Flink keeps EXTRACT.
343
+ EXTRACT_FUNCTIONS: dict = {}
344
+
345
+ NO_PAREN_FUNCTION_PARSERS = {
346
+ **SparkParser.NO_PAREN_FUNCTION_PARSERS,
347
+ "MAP": lambda self: self._parse_map_constructor(),
348
+ }
349
+
350
+ FUNCTION_PARSERS = {
351
+ **SparkParser.FUNCTION_PARSERS,
352
+ "JSON_VALUE": lambda self: self._parse_json_value(),
353
+ "FLOOR": lambda self: self._parse_floor(),
354
+ }
355
+ # Spark's SUBSTR parser marks a zero start; Flink's SUBSTR is plain SUBSTRING.
356
+ FUNCTION_PARSERS.pop("SUBSTR", None)
357
+
358
+ # DATE '2024-01-01', TIME '10:00:00' and TIMESTAMP '...' are kept as typed
359
+ # literals rather than turned into casts, so they round-trip as written.
360
+ TYPE_LITERAL_PARSERS = {
361
+ **SparkParser.TYPE_LITERAL_PARSERS,
362
+ **{
363
+ dtype: lambda self, this, data_type: _typed_literal(
364
+ self.expression(exp.Cast(this=this, to=data_type))
365
+ )
366
+ for dtype in (exp.DType.DATE, exp.DType.TIME, exp.DType.TIMESTAMP)
367
+ },
368
+ }
369
+
370
+ CONSTRAINT_PARSERS = {
371
+ **SparkParser.CONSTRAINT_PARSERS,
372
+ "METADATA": lambda self: self._parse_metadata_constraint(),
373
+ "WATERMARK": lambda self: self.expression(
374
+ exp.WatermarkColumnConstraint(
375
+ this=self._match(TokenType.FOR) and self._parse_column(),
376
+ expression=self._match(TokenType.ALIAS) and self._parse_disjunction(),
377
+ )
378
+ ),
379
+ }
380
+
381
+ SCHEMA_UNNAMED_CONSTRAINTS = {*SparkParser.SCHEMA_UNNAMED_CONSTRAINTS, "WATERMARK"}
382
+
383
+ def _parse_floor(self) -> exp.Expr:
384
+ # FLOOR(ts TO DAY) is Flink's DATE_TRUNC.
385
+ floor = self._parse_ceil_floor(exp.Floor)
386
+ unit = floor.args.get("to")
387
+ if unit is not None:
388
+ return exp.TimestampTrunc(this=floor.this, unit=exp.var(unit.name.upper()))
389
+ return floor
390
+
391
+ def _parse_map_constructor(self) -> exp.Expr | None:
392
+ # MAP['a', 1, 'b', 2]; MAP(...) and the MAP<K, V> type parse elsewhere.
393
+ if not self._match(TokenType.L_BRACKET):
394
+ self._retreat(self._index - 1)
395
+ return None
396
+ args = self._parse_csv(self._parse_disjunction)
397
+ self._match(TokenType.R_BRACKET)
398
+ return parser.build_var_map(args)
399
+
400
+ def _parse_metadata_constraint(self) -> exp.Expr:
401
+ # METADATA [FROM 'key'] [VIRTUAL]
402
+ key = self._parse_string() if self._match(TokenType.FROM) else None
403
+ virtual = self._match_text_seq("VIRTUAL")
404
+ return self.expression(MetadataColumnConstraint(this=key, virtual=virtual or None))
405
+
406
+ def _parse_types(
407
+ self,
408
+ check_func: bool = False,
409
+ schema: bool = False,
410
+ allow_identifiers: bool = True,
411
+ with_collation: bool = False,
412
+ ) -> exp.Expr | None:
413
+ # Unlike Spark, Flink honours CHAR(n) and VARCHAR(n) in casts, so skip
414
+ # Hive's rewrite of them to STRING.
415
+ this = parser.Parser._parse_types(
416
+ self,
417
+ check_func=check_func,
418
+ schema=schema,
419
+ allow_identifiers=allow_identifiers,
420
+ with_collation=with_collation,
421
+ )
422
+ # In Flink, CHAR, VARCHAR, BINARY and VARBINARY without a length have
423
+ # length 1. Spell that out, since other dialects read them as unbounded.
424
+ if isinstance(this, exp.DataType):
425
+ for node in this.find_all(exp.DataType):
426
+ if node.this in _LENGTH_ONE_TYPES and not node.expressions:
427
+ node.set("expressions", [exp.DataTypeParam(this=exp.Literal.number(1))])
428
+ return this
429
+
430
+ def _parse_equality(self, parse_is: bool = True) -> exp.Expr | None:
431
+ # Calcite's precedence, not Spark's left-to-right grouping of comparisons.
432
+ return parser.Parser._parse_equality(self)
433
+
434
+ def _parse_substring(self) -> exp.Substring:
435
+ # Flink's SUBSTRING is the standard one: 1-based, no Spark zero start.
436
+ return parser.Parser._parse_substring(self)
437
+
438
+ def _parse_table_function_arg(self) -> exp.Expr | None:
439
+ # TABLE t [PARTITION BY ...] as an argument of a table function such as
440
+ # TUMBLE(TABLE t, DESCRIPTOR(ts), INTERVAL '1' HOUR).
441
+ if not (
442
+ self._curr
443
+ and self._curr.token_type == TokenType.TABLE
444
+ and self._next
445
+ and self._next.token_type in self.ID_VAR_TOKENS
446
+ ):
447
+ return None
448
+ comments = self._curr.comments
449
+ self._advance()
450
+ table = self._parse_table_parts()
451
+ partition = self._parse_partition_by()
452
+ return self.expression(
453
+ FlinkTableArgument(this=table, partition=partition or None), comments=comments
454
+ )
455
+
456
+ def _parse_lambda(self, alias: bool = False) -> exp.Expr | None:
457
+ return self._parse_table_function_arg() or super()._parse_lambda(alias=alias)
458
+
459
+ def _parse_table_parts(self, *args, **kwargs) -> exp.Table:
460
+ table = super()._parse_table_parts(*args, **kwargs)
461
+ # Dynamic table options right after the name: t /*+ OPTIONS('k'='v') */.
462
+ while self._match(TokenType.HINT):
463
+ hint = self._prev_comments and exp.maybe_parse(
464
+ self._prev_comments[0], into=exp.Hint, dialect=self.dialect
465
+ )
466
+ if hint:
467
+ table.append("hints", hint)
468
+ # The hint's text is not also a comment on the next expression.
469
+ self._prev.comments = []
470
+ self._prev_comments = None
471
+ return table
472
+
473
+
474
+ class MetadataColumnConstraint(exp.Expression, exp.ColumnConstraintKind):
475
+ """Flink's METADATA [FROM 'key'] [VIRTUAL] column."""
476
+
477
+ arg_types = {"this": False, "virtual": False}
478
+
479
+
480
+ class FlinkTableArgument(exp.Expression):
481
+ """TABLE t [PARTITION BY ...], a table passed to a table function."""
482
+
483
+ arg_types = {"this": True, "partition": False}
484
+
485
+
486
+ class FlinkGenerator(SparkGenerator):
487
+ QUERY_HINTS = True
488
+ TABLE_HINTS = False # written by table_parts, before FOR SYSTEM_TIME and the alias
489
+ WITH_PROPERTIES_PREFIX = "WITH"
490
+ SUPPORTS_TEMPORAL_PRECISION = True
491
+ LIMIT_FETCH = "LIMIT"
492
+ INTERVAL_ALLOWS_PLURAL_FORM = False
493
+ SINGLE_STRING_INTERVAL = False
494
+ WRAP_DERIVED_VALUES = True
495
+ # Words Flink reserves, which must be quoted to name a column or table.
496
+ RESERVED_KEYWORDS = {
497
+ "all", "and", "array", "as", "between", "by", "case", "cast", "current", "date",
498
+ "day", "default", "desc", "distinct", "drop", "else", "end", "except", "exists",
499
+ "false", "fetch", "filter", "for", "from", "full", "function", "group", "having",
500
+ "hour", "in", "inner", "insert", "interval", "intersect", "into", "is", "join",
501
+ "language", "left", "like", "limit", "local", "map", "match_recognize", "minute",
502
+ "month", "multiset", "natural", "not", "null", "of", "offset", "on", "or", "order",
503
+ "outer", "over", "partition", "range", "raw", "right", "row", "rows", "second",
504
+ "select", "set", "system_time", "table", "then", "time", "timestamp", "to", "true",
505
+ "union", "unknown", "user", "using", "value", "values", "when", "where", "window",
506
+ "with", "year",
507
+ } # fmt: skip
508
+
509
+ PROPERTIES_LOCATION = {
510
+ **SparkGenerator.PROPERTIES_LOCATION,
511
+ exp.Property: exp.Properties.Location.POST_WITH,
512
+ exp.PartitionedByProperty: exp.Properties.Location.POST_SCHEMA,
513
+ exp.SchemaCommentProperty: exp.Properties.Location.POST_SCHEMA,
514
+ }
515
+
516
+ TYPE_MAPPING = {
517
+ **SparkGenerator.TYPE_MAPPING,
518
+ exp.DType.DATETIME: "TIMESTAMP",
519
+ exp.DType.TIMESTAMPNTZ: "TIMESTAMP",
520
+ exp.DType.TIMESTAMPTZ: "TIMESTAMP_LTZ",
521
+ exp.DType.TIMESTAMPLTZ: "TIMESTAMP_LTZ",
522
+ exp.DType.TIME: "TIME",
523
+ exp.DType.VARBINARY: "VARBINARY",
524
+ exp.DType.BLOB: "BYTES",
525
+ exp.DType.JSON: "STRING",
526
+ exp.DType.UUID: "STRING",
527
+ exp.DType.STRUCT: "ROW",
528
+ exp.DType.LIST: "MULTISET",
529
+ exp.DType.NULL: "NULL",
530
+ }
531
+
532
+ TRANSFORMS = {
533
+ **SparkGenerator.TRANSFORMS,
534
+ exp.ArraySize: _array_size_sql,
535
+ exp.CurrentTimestamp: lambda self, e: "CURRENT_TIMESTAMP",
536
+ exp.DateAdd: _timestampadd_sql,
537
+ exp.DateSub: _timestampsub_sql,
538
+ exp.DateDiff: _timestampdiff_sql,
539
+ exp.DatetimeAdd: _timestampadd_sql,
540
+ exp.DatetimeSub: _timestampsub_sql,
541
+ exp.DatetimeDiff: _timestampdiff_sql,
542
+ exp.TimestampAdd: _timestampadd_sql,
543
+ exp.TimestampSub: _timestampsub_sql,
544
+ exp.TimestampDiff: _timestampdiff_sql,
545
+ exp.TsOrDsAdd: _timestampadd_sql,
546
+ exp.DateTrunc: _trunc_sql,
547
+ exp.TimestampTrunc: _trunc_sql,
548
+ exp.GroupConcat: _group_concat_sql,
549
+ # Flink has no ILIKE.
550
+ exp.ILike: no_ilike_sql,
551
+ exp.Lateral: explode_to_unnest_sql,
552
+ exp.Variance: rename_func("VAR_SAMP"),
553
+ exp.IntDiv: _int_div_sql,
554
+ exp.JSONExtract: _json_query_sql,
555
+ exp.JSONExtractScalar: _json_value_sql,
556
+ exp.Length: rename_func("CHAR_LENGTH"),
557
+ exp.RegexpLike: rename_func("REGEXP"),
558
+ exp.StrPosition: _str_position_sql,
559
+ exp.StrToDate: _str_to_date_sql,
560
+ exp.StrToTime: _str_to_time_sql,
561
+ exp.StrToUnix: _str_to_unix_sql,
562
+ exp.TsOrDsToDate: _ts_or_ds_to_date_sql,
563
+ exp.UnixToStr: _unix_to_str_sql,
564
+ exp.UnixToTime: _unix_to_time_sql,
565
+ exp.Select: transforms.preprocess(
566
+ [
567
+ _qualify_keeping_order,
568
+ transforms.eliminate_distinct_on,
569
+ transforms.explode_projection_to_unnest(1),
570
+ ]
571
+ ),
572
+ exp.Unnest: lambda self, e: generator.Generator.unnest_sql(self, e),
573
+ exp.Create: lambda self, e: generator.Generator.create_sql(self, e),
574
+ exp.Property: lambda self, e: (
575
+ f"{self.sql(exp.Literal.string(e.name))} = {self.sql(e, 'value')}"
576
+ ),
577
+ exp.Substring: lambda self, e: self.func(
578
+ "SUBSTRING", e.this, e.args.get("start"), e.args.get("length")
579
+ ),
580
+ exp.DPipe: lambda self, e: self.binary(e, "||"),
581
+ exp.TryCast: lambda self, e: (
582
+ self.trycast_sql(e) if e.args.get("safe") else self.cast_sql(e)
583
+ ),
584
+ exp.UnixSeconds: lambda self, e: self.func("UNIX_TIMESTAMP", e.this),
585
+ exp.ApproxDistinct: lambda self, e: self.func("APPROX_COUNT_DISTINCT", e.this),
586
+ exp.ToBase64: rename_func("TO_BASE64"),
587
+ exp.FromBase64: rename_func("FROM_BASE64"),
588
+ exp.StrToMap: lambda self, e: self.func(
589
+ "STR_TO_MAP",
590
+ e.this,
591
+ *(
592
+ []
593
+ if e.args.get("pair_delim") == exp.Literal.string(",")
594
+ and e.args.get("key_value_delim") == exp.Literal.string("=")
595
+ else [e.args.get("pair_delim"), e.args.get("key_value_delim")]
596
+ ),
597
+ ),
598
+ exp.VarMap: lambda self, e: _map_sql(self, e),
599
+ exp.Map: lambda self, e: _map_sql(self, e),
600
+ exp.JSONKeyValue: lambda self, e: (
601
+ f"{self.sql(e, 'this')} VALUE {self.sql(e, 'expression')}"
602
+ ),
603
+ exp.Array: lambda self, e: f"ARRAY[{self.expressions(e, flat=True)}]",
604
+ exp.ComputedColumnConstraint: lambda self, e: f"AS {self.sql(e, 'this')}",
605
+ MetadataColumnConstraint: lambda self, e: (
606
+ "METADATA"
607
+ + (f" FROM {self.sql(e, 'this')}" if e.this else "")
608
+ + (" VIRTUAL" if e.args.get("virtual") else "")
609
+ ),
610
+ FlinkTableArgument: lambda self, e: (
611
+ f"TABLE {self.table_parts(e.this)}"
612
+ + (
613
+ f" PARTITION BY {self.expressions(e, key='partition', flat=True)}"
614
+ if e.args.get("partition")
615
+ else ""
616
+ )
617
+ ),
618
+ }
619
+
620
+ def table_parts(self, expression: exp.Table) -> str:
621
+ sql = super().table_parts(expression)
622
+ hints = expression.args.get("hints")
623
+ if hints:
624
+ sql += " " + " ".join(
625
+ f"/*+ {self.expressions(h, sep=', ').strip()} */"
626
+ if isinstance(h, exp.Hint)
627
+ else self.sql(h)
628
+ for h in hints
629
+ )
630
+ return sql
631
+
632
+ def cast_sql(self, expression: exp.Cast, safe_prefix: str | None = None) -> str:
633
+ if expression.meta.get("typed_literal") and expression.this.is_string:
634
+ return f"{self.sql(expression, 'to')} {self.sql(expression, 'this')}"
635
+ return super().cast_sql(expression, safe_prefix=safe_prefix)
636
+
637
+ def not_sql(self, expression: exp.Not) -> str:
638
+ # x IS NOT NULL rather than NOT x IS NULL; both mean the same in Flink.
639
+ this = expression.this
640
+ if isinstance(this, exp.Is):
641
+ return f"{self.sql(this, 'this')} IS NOT {self.sql(this, 'expression')}"
642
+ if isinstance(this, (exp.In, exp.Between)):
643
+ left = self.sql(this, "this")
644
+ sql = self.sql(this)
645
+ if sql.startswith(f"{left} "):
646
+ return f"{left} NOT {sql[len(left) + 1 :]}"
647
+ return super().not_sql(expression)
648
+
649
+ def log_sql(self, expression: exp.Log) -> str:
650
+ base, value = expression.this, expression.expression
651
+ if value is None:
652
+ # A one-argument LOG from another dialect is base 10; Flink's own
653
+ # one-argument LOG is the natural log and parses as LN.
654
+ return self.func("LOG10", base)
655
+ if base.is_int and base.name in ("2", "10"):
656
+ return self.func(f"LOG{base.name}", value)
657
+ return self.func("LOG", base, value)
658
+
659
+ def trunc_sql(self, expression: exp.Trunc) -> str:
660
+ return self.func("TRUNCATE", expression.this, expression.args.get("decimals"))
661
+
662
+ def format_time(self, expression: exp.Expr, *args, **kwargs) -> str | None:
663
+ # Spark's generator writes parse patterns leniently (M for MM); Flink's
664
+ # patterns are written as they are.
665
+ return generator.Generator.format_time(self, expression, *args, **kwargs)
666
+
667
+ def version_sql(self, expression: exp.Version) -> str:
668
+ # Temporal joins: FOR SYSTEM_TIME AS OF o.order_time.
669
+ return f"FOR SYSTEM_TIME AS OF {self.sql(expression, 'expression')}"
670
+
671
+ def datatype_sql(self, expression: exp.DataType) -> str:
672
+ this = expression.this
673
+ if this in (exp.DType.VARBINARY, exp.DType.BINARY) and not expression.expressions:
674
+ # Unbounded binary from another dialect; Flink's BINARY is BINARY(1).
675
+ return "BYTES"
676
+ if this in (exp.DType.VARCHAR, exp.DType.NVARCHAR) and not expression.expressions:
677
+ return "STRING"
678
+ if this == exp.DType.STRUCT and expression.args.get("nested"):
679
+ fields = ", ".join(
680
+ f"{self.sql(f, 'this')} {self.sql(f, 'kind')}"
681
+ if isinstance(f, exp.ColumnDef)
682
+ else self.sql(f)
683
+ for f in expression.expressions
684
+ )
685
+ return f"ROW<{fields}>"
686
+ return generator.Generator.datatype_sql(self, expression)
687
+
688
+ def unnest_sql(self, expression: exp.Unnest) -> str:
689
+ return generator.Generator.unnest_sql(self, expression)
690
+
691
+ def struct_sql(self, expression: exp.Struct) -> str:
692
+ # ROW(a, b): Flink's row constructor has no field names.
693
+ values = [
694
+ e.expression if isinstance(e, exp.PropertyEQ) else e for e in expression.expressions
695
+ ]
696
+ return self.func("ROW", *values)
697
+
698
+ def columndef_sql(self, expression: exp.ColumnDef, sep: str = " ") -> str:
699
+ return generator.Generator.columndef_sql(self, expression, sep)
700
+
701
+ def schema_sql(self, expression: exp.Schema) -> str:
702
+ return generator.Generator.schema_sql(self, expression)
703
+
704
+ def constraint_sql(self, expression: exp.Constraint) -> str:
705
+ return generator.Generator.constraint_sql(self, expression)
706
+
707
+ def parameter_sql(self, expression: exp.Parameter) -> str:
708
+ return generator.Generator.parameter_sql(self, expression)
709
+
710
+ def ignorenulls_sql(self, expression: exp.IgnoreNulls) -> str:
711
+ return generator.Generator.ignorenulls_sql(self, expression)
712
+
713
+ def dateadd_sql(self, expression: exp.DateAdd | exp.DateSub) -> str:
714
+ return _timestampadd_sql(self, expression)
715
+
716
+ def datesub_sql(self, expression: exp.DateSub) -> str:
717
+ return _timestampsub_sql(self, expression)
718
+
719
+ def arrayagg_sql(self, expression: exp.ArrayAgg) -> str:
720
+ return self.func("ARRAY_AGG", expression.this)
721
+
722
+ def interval_sql(self, expression: exp.Interval) -> str:
723
+ return generator.Generator.interval_sql(self, expression)
724
+
725
+
726
+ class Flink(Spark):
727
+ """Flink SQL, as accepted by Flink's SQL client and SQL Gateway.
728
+
729
+ Identifiers are quoted with backticks and are case-sensitive; strings use
730
+ single quotes, with '' for a quote inside one and no backslash escapes.
731
+ """
732
+
733
+ NORMALIZATION_STRATEGY = NormalizationStrategy.CASE_SENSITIVE
734
+ # 7 / 2 is 3 in Flink: integer division truncates, like Java's.
735
+ TYPED_DIVISION = True
736
+ # 1 / 0 fails the job with "Division by zero"; it does not return NULL.
737
+ SAFE_DIVISION = False
738
+ # CONCAT returns NULL when any argument is NULL; CONCAT_WS skips NULLs.
739
+ CONCAT_COALESCE = False
740
+ STRICT_STRING_CONCAT = False
741
+ CONCAT_WS_COALESCE = True
742
+ LOG_BASE_FIRST = True
743
+ NULL_ORDERING = "nulls_are_small"
744
+ UNESCAPED_SEQUENCES: dict[str, str] = {}
745
+ TIME_FORMAT = f"'{DEFAULT_TIME_FORMAT}'"
746
+ # REGEXP_EXTRACT(s, regex) without an index returns the whole match.
747
+ REGEXP_EXTRACT_DEFAULT_GROUP = 0
748
+ # ARRAY[1, 2][1] is 1: Flink arrays are 1-based.
749
+ INDEX_OFFSET = 1
750
+
751
+ # Java DateTimeFormatter patterns, as TO_TIMESTAMP, DATE_FORMAT and
752
+ # FROM_UNIXTIME take them.
753
+ TIME_MAPPING = {
754
+ "yyyy": "%Y",
755
+ "yy": "%y",
756
+ "MMMM": "%B",
757
+ "MMM": "%b",
758
+ "MM": "%m",
759
+ "M": "%-m",
760
+ "dd": "%d",
761
+ "d": "%-d",
762
+ "HH": "%H",
763
+ "H": "%-H",
764
+ "hh": "%I",
765
+ "h": "%-I",
766
+ "mm": "%M",
767
+ "m": "%-M",
768
+ "ss": "%S",
769
+ "s": "%-S",
770
+ "SSSSSS": "%f",
771
+ "a": "%p",
772
+ "DD": "%j",
773
+ "EEEE": "%A",
774
+ "EEE": "%a",
775
+ "Z": "%z",
776
+ "z": "%Z",
777
+ }
778
+
779
+ class Tokenizer(Spark.Tokenizer):
780
+ QUOTES = ["'"]
781
+ IDENTIFIERS = ["`"]
782
+ STRING_ESCAPES = ["'"]
783
+ RAW_STRINGS: list = []
784
+ NUMERIC_ESCAPES: dict = {}
785
+ NUMERIC_LITERALS: dict = {}
786
+ DROP_UNKNOWN_ESCAPES = False
787
+ # Lets the parser see /*+ OPTIONS(...) */ after a table name as a hint.
788
+ TOKENS_PRECEDING_HINT = {
789
+ *Spark.Tokenizer.TOKENS_PRECEDING_HINT,
790
+ TokenType.VAR,
791
+ TokenType.IDENTIFIER,
792
+ }
793
+
794
+ KEYWORDS = {
795
+ **Spark.Tokenizer.KEYWORDS,
796
+ "BYTES": TokenType.BLOB,
797
+ "MATCH_RECOGNIZE": TokenType.MATCH_RECOGNIZE,
798
+ "MULTISET": TokenType.LIST,
799
+ "ROW": TokenType.STRUCT,
800
+ "STRING": TokenType.TEXT,
801
+ "TIMESTAMP_LTZ": TokenType.TIMESTAMPLTZ,
802
+ # Spark reads TIMESTAMP as TIMESTAMP_LTZ; in Flink it has no time zone.
803
+ "TIMESTAMP": TokenType.TIMESTAMP,
804
+ }
805
+ SINGLE_TOKENS = dict(Spark.Tokenizer.SINGLE_TOKENS)
806
+ # $ is part of names such as EXPR$0, not a parameter marker.
807
+ SINGLE_TOKENS.pop("$", None)
808
+
809
+ for _key in ("<=>", "MINUS", "DIV", "SESSION"):
810
+ KEYWORDS.pop(_key, None)
811
+ del _key
812
+
813
+ Parser = FlinkParser
814
+
815
+ Generator = FlinkGenerator
@@ -0,0 +1,196 @@
1
+ Metadata-Version: 2.5
2
+ Name: sqlglot-flink
3
+ Version: 0.1.0
4
+ Summary: sqlglot-flink, a Flink SQL dialect for sqlglot
5
+ Project-URL: Homepage, https://github.com/hashroute3/sqlglot-flink
6
+ Project-URL: Issues, https://github.com/hashroute3/sqlglot-flink/issues
7
+ Author-email: Mahendran Vasagam <mahendran.vasagam@gmail.com>
8
+ License-Expression: Apache-2.0
9
+ License-File: LICENSE
10
+ Keywords: dialect,flink,flink-sql,sql,sqlglot,streaming,transpiler
11
+ Classifier: Development Status :: 3 - Alpha
12
+ Classifier: Intended Audience :: Developers
13
+ Classifier: License :: OSI Approved :: Apache Software License
14
+ Classifier: Programming Language :: Python :: 3
15
+ Classifier: Programming Language :: SQL
16
+ Classifier: Topic :: Database
17
+ Requires-Python: >=3.10
18
+ Requires-Dist: sqlglot>=30.0
19
+ Provides-Extra: dev
20
+ Requires-Dist: pytest>=8; extra == 'dev'
21
+ Requires-Dist: ruff>=0.6; extra == 'dev'
22
+ Description-Content-Type: text/markdown
23
+
24
+ # sqlglot-flink
25
+
26
+ sqlglot-flink, a Flink SQL dialect for [sqlglot](https://github.com/tobymao/sqlglot),
27
+ packaged as a
28
+ [sqlglot dialect plugin](https://github.com/tobymao/sqlglot#creating-a-dialect-plugin).
29
+
30
+ With it, sqlglot can turn SQL written for another engine into SQL Flink runs,
31
+ turn Flink SQL into SQL for other engines, and parse and regenerate Flink SQL,
32
+ including its streaming syntax, without breaking it.
33
+
34
+ ```python
35
+ import sqlglot
36
+
37
+ sqlglot.transpile(
38
+ "SELECT DATE_TRUNC('hour', ts), STRPOS(s, 'x'), 7 / 2, s ILIKE 'a%' FROM t",
39
+ read="postgres",
40
+ write="flink",
41
+ )
42
+ # ["SELECT FLOOR(ts TO HOUR), POSITION('x' IN s), 7 / 2, LOWER(s) LIKE LOWER('a%') FROM t"]
43
+
44
+ sqlglot.transpile("SELECT FLOOR(ts TO DAY), LOCATE('b', s) FROM t", read="flink", write="duckdb")
45
+ # ["SELECT DATE_TRUNC('DAY', ts), STRPOS(s, 'b') FROM t"]
46
+ ```
47
+
48
+ ## Install
49
+
50
+ ```bash
51
+ pip install sqlglot-flink
52
+ ```
53
+
54
+ Installing the package registers the dialect with sqlglot under the name
55
+ `flink`; there is nothing to import. You can also use the class directly:
56
+
57
+ ```python
58
+ from sqlglot_flink import Flink
59
+ ```
60
+
61
+ Requires Python 3.10+ and sqlglot 30 or later.
62
+
63
+ ## What it handles
64
+
65
+ The dialect builds on sqlglot's Spark dialect. Flink's built-in functions copy
66
+ much of the Hive library (`DATE_FORMAT`, `FROM_UNIXTIME`, `UNIX_TIMESTAMP`,
67
+ `REGEXP_EXTRACT`, `STR_TO_MAP`, backtick identifiers), which Hive and Spark
68
+ share, and Spark adds what Flink also has: `TRY_CAST`, `TO_TIMESTAMP(s, fmt)`,
69
+ `TIMESTAMPADD`/`TIMESTAMPDIFF(unit, ...)`, the `TIMESTAMP_LTZ` type and
70
+ `/*+ ... */` query hints. Where Flink follows Apache Calcite instead, the
71
+ dialect overrides Spark.
72
+
73
+ Flink SQL that round-trips:
74
+
75
+ - backtick identifiers, case-sensitive; reserved words such as `value` and
76
+ `raw` stay quoted; strings in single quotes with `''`, no backslash escapes;
77
+ - types `STRING`, `BYTES`, `TIMESTAMP(p)`, `TIMESTAMP_LTZ(p)` (and
78
+ `TIMESTAMP(p) WITH LOCAL TIME ZONE`), `ARRAY<T>`, `MAP<K, V>`,
79
+ `ROW<a INT, b STRING>`, `MULTISET<T>`, `ARRAY[...]`, `MAP[...]`, `ROW(...)`;
80
+ - window table-valued functions `TUMBLE`, `HOP`, `CUMULATE` and `SESSION`
81
+ over `TABLE t [PARTITION BY ...]` and `DESCRIPTOR(ts)`, with positional or
82
+ named (`DATA => ...`) arguments;
83
+ - temporal joins (`FOR SYSTEM_TIME AS OF o.order_time`), `OVER` windows with
84
+ `RANGE BETWEEN INTERVAL ... PRECEDING`, named `WINDOW` clauses;
85
+ - dynamic table options `t /*+ OPTIONS('k'='v') */` and join hints
86
+ `SELECT /*+ BROADCAST(t) */`;
87
+ - `CREATE TABLE` with computed columns, `METADATA [FROM 'key'] [VIRTUAL]`
88
+ columns, `WATERMARK FOR ts AS ts - INTERVAL '5' SECOND`,
89
+ `PRIMARY KEY (...) NOT ENFORCED`, `PARTITIONED BY` and `WITH (...)`;
90
+ - `MATCH_RECOGNIZE`, `CROSS JOIN UNNEST`, `CURRENT_WATERMARK`, `LISTAGG`,
91
+ `COLLECT`, `JSON_VALUE(... RETURNING ...)`, `JSON_OBJECT(k VALUE v)`.
92
+
93
+ SQL from other dialects, translated to what Flink spells or means differently:
94
+
95
+ | Other dialects | Flink SQL generated |
96
+ |---|---|
97
+ | `DATE_TRUNC('day', ts)` | `FLOOR(ts TO DAY)` |
98
+ | `DATE_DIFF('day', a, b)`, `DATEDIFF(b, a)` | `TIMESTAMPDIFF(DAY, a, b)` |
99
+ | `DATE_ADD('hour', 3, ts)`, `DATE_ADD(d, 1)` | `TIMESTAMPADD(HOUR, 3, ts)`, `TIMESTAMPADD(DAY, 1, d)` |
100
+ | `LENGTH(s)` | `CHAR_LENGTH(s)` |
101
+ | `STRPOS(s, x)`, `INSTR(s, x)` | `POSITION(x IN s)` |
102
+ | `s ILIKE p` | `LOWER(s) LIKE LOWER(p)` (Flink has no `ILIKE`) |
103
+ | `s ~ p`, `s RLIKE p` | `REGEXP(s, p)` |
104
+ | `STRING_AGG(x, ',')` | `LISTAGG(x)` |
105
+ | `x ->> 'a'`, `GET_JSON_OBJECT(x, '$.a')` | `JSON_VALUE(x, '$.a')` |
106
+ | `LATERAL VIEW EXPLODE(arr) t AS x` | `CROSS JOIN UNNEST(arr) AS t(x)` |
107
+ | `TO_TIMESTAMP(epoch)` (DuckDB) | `TO_TIMESTAMP_LTZ(epoch, 0)` |
108
+ | `STRFTIME`, `TO_CHAR` patterns | Java patterns: `DATE_FORMAT(ts, 'yyyy-MM-dd')` |
109
+ | `VARCHAR`, `TEXT`, `BYTEA`, unbounded `BINARY` | `STRING`, `BYTES` |
110
+ | `TIMESTAMPTZ` | `TIMESTAMP_LTZ` |
111
+ | `LOG(x)` (Postgres, base 10) | `LOG10(x)` |
112
+ | `QUALIFY ...` | a filtered subquery |
113
+
114
+ ### Where Flink's semantics differ
115
+
116
+ These are tested against a live Flink, by value, not only by acceptance:
117
+
118
+ - **Integer division truncates.** `7 / 2` is 3 and `-7 / 2` is -3, as in
119
+ Postgres and Trino. DuckDB's and Spark's `/` divides as doubles, so their
120
+ `7 / 2` becomes `CAST(7 AS DOUBLE) / 2`; `7 // 2` and `7 DIV 2` become
121
+ `CAST(7 / 2 AS BIGINT)`.
122
+ - **Division by zero fails the job.** Spark returns NULL, so a Spark divisor
123
+ is wrapped in `NULLIF(d, 0)`.
124
+ - **String positions are 1-based** and 0 means absent, like the standard, so
125
+ `POSITION`, `LOCATE` and `SUBSTRING` keep their arguments.
126
+ - **`CONCAT` returns NULL if any argument is NULL** (`CONCAT_WS` skips
127
+ NULLs). Postgres skips them, so its arguments get `COALESCE(x, '')`.
128
+ - **NULLs sort first in ascending order.** Postgres sorts them last, so its
129
+ `ORDER BY` gets an explicit `NULLS LAST`.
130
+ - **Arrays are 1-based**; Spark's `arr[0]` becomes `arr[1]`.
131
+ - **`LOG(x)` with one argument is the natural log**; it reads as `LN(x)`.
132
+ - **`REGEXP_EXTRACT(s, re)` without an index returns the whole match**,
133
+ where Hive and Spark return group 1, so Spark's call gets an explicit `1`.
134
+ - **`CHAR`, `VARCHAR`, `BINARY` and `VARBINARY` without a length mean length
135
+ 1.** Flink SQL's `CAST(x AS VARCHAR)` is written as `VARCHAR(1)`; the
136
+ unbounded `VARCHAR` of other dialects becomes `STRING`.
137
+ - **`STR_TO_MAP(s)` splits on `,` and `=`** (Hive uses `:`).
138
+
139
+ ## How it is tested
140
+
141
+ [`tests/corpus.py`](tests/corpus.py) is a set of queries over deterministic
142
+ tables (views over `VALUES` and a bounded datagen table) that the tests create
143
+ in each session:
144
+
145
+ - 131 Flink queries that must round-trip, 116 of them with expected rows;
146
+ - 81 queries from Postgres, Spark, DuckDB, Trino and MySQL that must become
147
+ the expected Flink SQL, all with expected rows.
148
+
149
+ The unit tests check the generated SQL text. The live tests send every corpus
150
+ query, and every generated query, to a real Flink SQL Gateway: batch queries
151
+ run in batch mode and their rows are compared; queries Flink only accepts in
152
+ streaming mode (session windows, temporal joins, `OVER ... RANGE` with an
153
+ interval, `CURRENT_WATERMARK`) are planned with `EXPLAIN` in a streaming
154
+ session; DDL runs in a fresh session. All 212 pass on Flink 1.20.5 and 2.3.0,
155
+ and CI runs them against both.
156
+
157
+ ```bash
158
+ FLINK_VERSION=2.3.0 docker compose -f tests/docker-compose.yml up -d
159
+ FLINK_GATEWAY_URL=http://127.0.0.1:8083 pytest
160
+ docker compose -f tests/docker-compose.yml down
161
+ ```
162
+
163
+ `scripts/check_versions.sh 1.20.5 2.3.0` runs the same check against a fresh
164
+ cluster of each version; `scripts/live_check.py` prints every mismatch.
165
+
166
+ ## Limitations
167
+
168
+ - **`TIMESTAMPDIFF` counts whole units.** `DATE_DIFF('day', ...)` in DuckDB or
169
+ Trino counts day boundaries crossed, so for timestamps less than a day apart
170
+ across midnight they differ (1 against 0). Dates give the same answer.
171
+ - **Spark's `TIMESTAMP` is zoned**, so it becomes `TIMESTAMP_LTZ`, and results
172
+ carry the session time zone.
173
+ - **Not translated:** `BOOL_AND`/`BOOL_OR` (Flink has none), regular-expression
174
+ `SPLIT` (Flink's `SPLIT` takes a literal delimiter), `LISTAGG ... ORDER BY`,
175
+ `STATEMENT SET`, `EXECUTE`, and Flink-only DDL such as `CREATE CATALOG` or
176
+ `CREATE FUNCTION ... USING JAR`, which parse as sqlglot commands at best.
177
+ - **Flink-only functions pass through as written** (`SPLIT_INDEX`,
178
+ `CURRENT_WATERMARK`, `PROCTIME`, `DESCRIPTOR`, window TVFs); they are not
179
+ rewritten for other dialects.
180
+ - `INTERVAL '10' MINUTES` is written as `INTERVAL '10' MINUTE`, and
181
+ `IFNULL` as `COALESCE`.
182
+
183
+ ## Contributing
184
+
185
+ Bug reports and pull requests are welcome: see
186
+ [CONTRIBUTING.md](CONTRIBUTING.md) for how to report a problem, run the tests and
187
+ send a change. Report security problems privately, as described in
188
+ [SECURITY.md](SECURITY.md). Changes are listed in [CHANGELOG.md](CHANGELOG.md).
189
+
190
+ ## License
191
+
192
+ Apache License 2.0. See [LICENSE](LICENSE).
193
+
194
+ Apache Flink, Flink and the Flink logo are trademarks of the Apache Software
195
+ Foundation. This project is not affiliated with or endorsed by the Apache
196
+ Software Foundation.
@@ -0,0 +1,7 @@
1
+ sqlglot_flink/__init__.py,sha256=PT6hdGxr_5qYW8OzY1DSngdSMisiBmTwEOpdFARj_lI,325
2
+ sqlglot_flink/dialect.py,sha256=Jt7bC5iN6VDa1DgJeSj_37dZB3UspJh237grsjoMCVc,33246
3
+ sqlglot_flink-0.1.0.dist-info/METADATA,sha256=tEZaDcXFz_oimNBsgkwwkXIh3bVLWHFvqZ6wf4tFz0s,8888
4
+ sqlglot_flink-0.1.0.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
5
+ sqlglot_flink-0.1.0.dist-info/entry_points.txt,sha256=f86p8F5FuEj_TZslqn6zJa5ftE79ho7mOcpfBup6fcY,47
6
+ sqlglot_flink-0.1.0.dist-info/licenses/LICENSE,sha256=z8d0m5b2O9McPEK1xHG_dWgUBT6EfBDz6wA0F7xSPTA,11358
7
+ sqlglot_flink-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.33.0
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
@@ -0,0 +1,2 @@
1
+ [sqlglot.dialects]
2
+ flink = sqlglot_flink:Flink
@@ -0,0 +1,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright [yyyy] [name of copyright owner]
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.