tinybird 5.0.3.dev0__py3-none-any.whl → 5.0.4.dev0__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.
tinybird/sql_template.py CHANGED
@@ -1389,10 +1389,6 @@ _namespace = {
1389
1389
  "__doc__": {},
1390
1390
  "__name__": {},
1391
1391
  "__package__": {},
1392
- "open": None,
1393
- "close": None,
1394
- "print": None,
1395
- "input": None,
1396
1392
  }
1397
1393
 
1398
1394
 
@@ -1407,6 +1403,14 @@ reserved_vars.discard("id")
1407
1403
  error_vars = ["error", "custom_error"]
1408
1404
 
1409
1405
 
1406
+ _SQL_COMMENT_UNSAFE_CHARS = re.compile(r"[\x00-\x1f\x7f\u2028\u2029]")
1407
+
1408
+
1409
+ def _sql_comment_safe(value: Any) -> str:
1410
+ """Make a value safe to put in a `--` SQL comment: a line break would end the comment."""
1411
+ return _SQL_COMMENT_UNSAFE_CHARS.sub(" ", str(value))
1412
+
1413
+
1410
1414
  def generate(self, **kwargs) -> Tuple[str, TemplateExecutionResults]:
1411
1415
  """Generate this template with the given arguments."""
1412
1416
  namespace = {}
@@ -1447,16 +1451,17 @@ def generate(self, **kwargs) -> Tuple[str, TemplateExecutionResults]:
1447
1451
 
1448
1452
  def set_max_threads(x):
1449
1453
  try:
1450
- template_execution_results["max_threads"] = int(x)
1451
- return Expression(f"-- max_threads {x}\n")
1454
+ max_threads = int(x)
1452
1455
  except Exception:
1453
- return Expression(f"-- max_threads: wrong argument {x}\n")
1456
+ return Expression("-- max_threads: wrong argument\n")
1457
+ template_execution_results["max_threads"] = max_threads
1458
+ return Expression(f"-- max_threads {max_threads}\n")
1454
1459
 
1455
1460
  def set_backend_hint(hint):
1456
1461
  template_execution_results["backend_hint"] = str(hint)
1457
1462
  if hint is None or hint is False:
1458
1463
  template_execution_results["backend_hint"] = None
1459
- return Expression(f"-- backend_hint {hint}\n")
1464
+ return Expression(f"-- backend_hint {_sql_comment_safe(hint)}\n")
1460
1465
 
1461
1466
  def set_cache_ttl(ttl_expression):
1462
1467
  valid_ttl_expressions = ("5s", "1m", "5m", "30m", "1h")
@@ -1,11 +1,12 @@
1
1
  import logging
2
+ import re
2
3
  from dataclasses import dataclass
3
4
  from functools import partial
4
5
  from types import MethodType
5
- from typing import Any, Dict, List, Optional
6
+ from typing import Any, Dict, List, Optional, Sequence
6
7
 
7
8
  from sqlfmt import actions, api
8
- from sqlfmt.analyzer import Analyzer, Rule, group
9
+ from sqlfmt.analyzer import Analyzer
9
10
  from sqlfmt.comment import Comment
10
11
  from sqlfmt.dialect import ClickHouse
11
12
  from sqlfmt.exception import SqlfmtBracketError
@@ -14,7 +15,9 @@ from sqlfmt.line import Line
14
15
  from sqlfmt.mode import Mode
15
16
  from sqlfmt.node import Node, get_previous_token
16
17
  from sqlfmt.node_manager import NodeManager
17
- from sqlfmt.token import Token, TokenType
18
+ from sqlfmt.rule import Rule
19
+ from sqlfmt.rules.common import SQL_QUOTED_EXP, group
20
+ from sqlfmt.tokens import Token, TokenType
18
21
 
19
22
  # This class extends and monkey patches https://github.com/tconbeer/sqlfm
20
23
  INDENT = " " * 4
@@ -24,6 +27,15 @@ DEFAULT_FMT_LINE_LENGTH = 100
24
27
 
25
28
  @dataclass
26
29
  class TBLine(Line):
30
+ def render_with_comments(self, max_length: int) -> str:
31
+ # 0.11 counted the trailing newline when deciding whether a comment
32
+ # fits and moved overflowing inline comments above the SQL line.
33
+ if len(self.comments) == 1 and not self.comments[0].is_standalone:
34
+ comment = self.comments[0]
35
+ if len(str(self).rstrip()) + len(comment.render_inline()) >= max_length:
36
+ return comment.render_standalone(max_length - 1, self.prefix) + str(self)
37
+ return super().render_with_comments(max_length - 1)
38
+
27
39
  @property
28
40
  def prefix(self) -> str:
29
41
  """
@@ -37,11 +49,11 @@ class TBLine(Line):
37
49
 
38
50
 
39
51
  def from_nodes(
40
- cls,
52
+ _cls: type[Line],
41
53
  previous_node: Optional[Node],
42
54
  nodes: List[Node],
43
55
  comments: List[Comment],
44
- ) -> "Line":
56
+ ) -> Line:
45
57
  """
46
58
  Creates and returns a new line from a list of Nodes. Useful for line
47
59
  splitting and merging.
@@ -49,68 +61,63 @@ def from_nodes(
49
61
  Tinybird => Monkey patched to use `TBLine` and our own indentation logic.
50
62
  """
51
63
  if nodes:
52
- line = TBLine(
53
- previous_node=previous_node,
54
- nodes=nodes,
55
- comments=comments,
56
- formatting_disabled=nodes[0].formatting_disabled or nodes[-1].formatting_disabled,
57
- )
64
+ formatting_disabled = nodes[0].formatting_disabled + nodes[-1].formatting_disabled
58
65
  else:
59
- line = TBLine(
60
- previous_node=previous_node,
61
- nodes=nodes,
62
- comments=comments,
63
- formatting_disabled=previous_node.formatting_disabled if previous_node else False,
64
- )
66
+ formatting_disabled = previous_node.formatting_disabled if previous_node is not None else []
65
67
 
66
- return line
68
+ return TBLine(
69
+ previous_node=previous_node,
70
+ nodes=nodes,
71
+ comments=comments,
72
+ formatting_disabled=formatting_disabled,
73
+ )
67
74
 
68
75
 
69
- def _format_jinja_node(self, node: Node, max_length: int) -> bool:
76
+ def _format_jinja_node(self: JinjaFormatter, node: Node, max_length: int) -> bool:
70
77
  """
71
78
  Format a single jinja tag. No-ops for nodes that
72
- are not jinja. Returns True if the node was blackened
79
+ are not jinja. Returns True if the node was blackened.
73
80
  """
74
- if node.is_jinja:
75
- formatter = JinjaFormatter(TBMode())
76
- tag = JinjaTag.from_string(node.value, node.depth[0] + node.depth[1])
77
- if formatter.use_black:
78
- # Monkey patching black to not normalize strings
79
- old_format_str = formatter.code_formatter.black.format_str
80
-
81
- def format_str(string, mode=None):
82
- black_mode = formatter.code_formatter.black.Mode(
83
- line_length=mode.line_length, string_normalization=False
81
+ if not node.is_jinja:
82
+ return False
83
+
84
+ tag = JinjaTag.from_string(node.value, node.depth)
85
+ if self.use_black and self.code_formatter.black is not None:
86
+ # Monkey patch black to preserve quote style inside Tinybird templates.
87
+ black = self.code_formatter.black
88
+ if not getattr(black, "_tinybird_preserve_string_normalization", False):
89
+ old_format_str = black.format_str
90
+
91
+ def format_str(string: str, mode: Any = None) -> str:
92
+ black_mode = black.Mode(
93
+ line_length=mode.line_length if mode is not None else max_length,
94
+ string_normalization=False,
84
95
  )
85
96
  return old_format_str(string, mode=black_mode)
86
97
 
87
- # ugly way to monkeypatch the above function only once
88
- if "add_formatter_only_once" not in formatter.code_formatter.PY_RESERVED_WORDS:
89
- formatter.code_formatter.black.format_str = format_str
90
- formatter.code_formatter.PY_RESERVED_WORDS.append("add_formatter_only_once")
98
+ black.format_str = format_str # type: ignore[attr-defined]
99
+ black._tinybird_preserve_string_normalization = True # type: ignore[attr-defined]
91
100
 
92
- if tag.code and formatter.use_black:
93
- tag.code, tag.is_blackened = formatter.code_formatter.format_string(
94
- tag.code,
95
- max_length=tag.max_code_length(max_length),
96
- )
97
-
98
- if "{%" in node.value:
99
- parts = tag.code.split("\n")
100
- prefix = INDENT * (node.depth[0] + node.depth[1])
101
- if len(parts) > 1:
102
- tag.code = "\n".join([f"{prefix if i != 0 else ''}{part}" for i, part in enumerate(parts)])
101
+ if tag.code and self.use_black:
102
+ tag.code, tag.is_blackened = self.code_formatter.format_string(
103
+ tag.code,
104
+ max_length=tag.max_code_length(max_length),
105
+ )
103
106
 
104
- node.value = str(tag)
107
+ if "{%" in node.value:
108
+ parts = tag.code.split("\n")
109
+ prefix = INDENT * (node.depth[0] + node.depth[1])
110
+ if len(parts) > 1:
111
+ tag.code = "\n".join([f"{prefix if i != 0 else ''}{part}" for i, part in enumerate(parts)])
105
112
 
106
- return tag.is_blackened
113
+ node.value = str(tag)
107
114
 
108
- return False
115
+ return tag.is_blackened
109
116
 
110
117
 
111
118
  # Some monkey patching
112
- Line.from_nodes = MethodType(from_nodes, Line)
113
- JinjaFormatter._format_jinja_node = MethodType(_format_jinja_node, JinjaFormatter)
119
+ Line.from_nodes = MethodType(from_nodes, Line) # type: ignore[method-assign]
120
+ JinjaFormatter._format_jinja_node = _format_jinja_node # type: ignore[method-assign]
114
121
 
115
122
 
116
123
  class TinybirdNodeManager(NodeManager):
@@ -122,6 +129,8 @@ class TinybirdNodeManager(NodeManager):
122
129
  try:
123
130
  return super().create_node(token, previous_node)
124
131
  except SqlfmtBracketError:
132
+ if token.token == ">":
133
+ raise
125
134
  # we already have tb check and the toolset to check the SQL, no need for this extra validation
126
135
  prev_token, extra_whitespace = get_previous_token(previous_node)
127
136
  prefix = self.whitespace(token, prev_token, extra_whitespace)
@@ -131,12 +140,14 @@ class TinybirdNodeManager(NodeManager):
131
140
  previous_node=previous_node,
132
141
  prefix=prefix,
133
142
  value=value,
134
- formatting_disabled=False,
143
+ formatting_disabled=[],
135
144
  )
136
145
 
137
146
  def raise_on_mismatched_bracket(self, token: Token, last_bracket: Node) -> None:
138
- # we already have tb check and the toolset to check the SQL, no need for this extra validation
139
- pass
147
+ # sqlfmt first tries `>` as an angle bracket. Retry comparisons inside
148
+ # parentheses as operators instead of letting them consume the `(`.
149
+ if token.token == ">":
150
+ super().raise_on_mismatched_bracket(token, last_bracket)
140
151
 
141
152
  def standardize_value(self, token: Token) -> str:
142
153
  """
@@ -159,6 +170,205 @@ class TinybirdNodeManager(NodeManager):
159
170
  return token.token
160
171
 
161
172
 
173
+ def _replace_rules(rules: Sequence[Rule], override_rules_by_name: Dict[str, Rule]) -> List[Rule]:
174
+ """Replace rules by name, including nested sqlfmt rulesets."""
175
+ replaced_rules: List[Rule] = []
176
+ for rule in rules:
177
+ new_rule = override_rules_by_name.get(rule.name, rule)
178
+ action = new_rule.action
179
+ if isinstance(action, partial) and action.keywords:
180
+ keywords = dict(action.keywords)
181
+ changed = False
182
+ for key, value in keywords.items():
183
+ if isinstance(value, list) and all(isinstance(item, Rule) for item in value):
184
+ keywords[key] = _replace_rules(value, override_rules_by_name)
185
+ changed = True
186
+ if changed:
187
+ new_rule = Rule(
188
+ name=new_rule.name,
189
+ priority=new_rule.priority,
190
+ pattern=new_rule.pattern,
191
+ action=partial(action.func, *action.args, **keywords),
192
+ )
193
+ replaced_rules.append(new_rule)
194
+ return replaced_rules
195
+
196
+
197
+ def _has_inline_jinja_block(sql: str) -> bool:
198
+ """Return whether every Jinja control block has an inline body.
199
+
200
+ Opening tags can span several lines when their Python expression is long.
201
+ That formatting alone must not make an otherwise inline block look like a
202
+ multiline one. Match each opening tag with its end tag, then inspect only
203
+ the body between them. We conservatively skip the compatibility pass for
204
+ malformed or genuinely mixed templates, because the pass works on the
205
+ formatted output and cannot safely select individual blocks there.
206
+ """
207
+ tag_pattern = re.compile(
208
+ r"\{%-?\s*(?P<start>if|for)\b.*?-?%\}|"
209
+ r"\{%-?\s*end(?:\s+(?P<end>if|for))?\s*-?%\}",
210
+ flags=re.IGNORECASE | re.DOTALL,
211
+ )
212
+ blocks: List[tuple[int, str]] = []
213
+ has_control_block = False
214
+
215
+ for tag in tag_pattern.finditer(sql):
216
+ start_kind = tag.group("start")
217
+ if start_kind is not None:
218
+ has_control_block = True
219
+ blocks.append((tag.end(), start_kind.lower()))
220
+ continue
221
+
222
+ if not blocks:
223
+ return False
224
+
225
+ body_start, start_kind = blocks.pop()
226
+ end_kind = tag.group("end")
227
+ if end_kind is not None and end_kind.lower() != start_kind:
228
+ return False
229
+ if "\n" in sql[body_start : tag.start()]:
230
+ return False
231
+
232
+ return has_control_block and not blocks
233
+
234
+
235
+ def _preserve_inline_jinja_blocks(source_sql: str, formatted_sql: str, line_length: int) -> str:
236
+ """Keep Tinybird's old inline Jinja-block style when the input used it.
237
+
238
+ sqlfmt 0.28 formats recognized Jinja blocks structurally, which turns
239
+ ``{% if ... %} select 1 {% end %}`` into multiple lines. That is a valid
240
+ formatting choice, but it creates formatting-only diffs for existing CLI
241
+ users. Preserve the previous Tinybird style only for inputs that already had
242
+ inline block contents; multiline blocks still benefit from proper nested
243
+ block indentation.
244
+ """
245
+ if not _has_inline_jinja_block(source_sql):
246
+ return formatted_sql
247
+
248
+ lines = formatted_sql.splitlines()
249
+ compacted_lines: List[str] = []
250
+ branch_tag = re.compile(r"\{%-?\s*(if|for|elif|else)\b.*?-?%\}$", flags=re.IGNORECASE)
251
+ chain_tag = re.compile(r"\{%-?\s*(elif|else|end)\b", flags=re.IGNORECASE)
252
+
253
+ def single_line_body(at: int) -> Optional[str]:
254
+ """Return lines[at] when it is a one-line body followed by a tag line."""
255
+ if at + 1 >= len(lines):
256
+ return None
257
+ body = lines[at].strip()
258
+ # A multiline {{ expression }} must retain its newline: joining
259
+ # its opening {{ makes the next tb fmt pass undo this one.
260
+ if not body or body.startswith("{%") or (body.startswith("{{") and not body.endswith("}}")):
261
+ return None
262
+ return body if lines[at + 1].strip().startswith("{%") else None
263
+
264
+ inline_branch = re.compile(r"\{%-?\s*(elif|else)\b.*?-?%\}\s+[^{\s][^{]*$", flags=re.IGNORECASE)
265
+ open_tag: Optional[str] = None
266
+ index = 0
267
+ while index < len(lines):
268
+ line = lines[index]
269
+ stripped = line.strip()
270
+ # Only opening/branch tags can absorb an inline body in 0.11; joining
271
+ # text after {% end %} would move the following SQL clause or comment.
272
+ if open_tag is not None and "{%" not in stripped and stripped.endswith("%}"):
273
+ # Closing line of a tag whose long condition spans several lines.
274
+ last_tag = f"{open_tag} {stripped}"
275
+ open_tag = None
276
+ else:
277
+ last_tag = stripped[stripped.rfind("{%") :]
278
+ if "{%" in stripped and "%}" not in last_tag:
279
+ open_tag = last_tag
280
+ body = single_line_body(index + 1) if branch_tag.match(last_tag) else None
281
+ if body is None:
282
+ compacted_lines.append(line)
283
+ index += 1
284
+ continue
285
+
286
+ first = f"{line.rstrip()} {body}"
287
+ # Try to fold the whole if/elif/else/end chain onto one line.
288
+ chain = [first]
289
+ closed = False
290
+ cursor = index + 2
291
+ while cursor < len(lines) and chain_tag.match(lines[cursor].strip()):
292
+ tag_line = lines[cursor].strip()
293
+ cursor += 1
294
+ if re.match(r"\{%-?\s*end\b", tag_line, flags=re.IGNORECASE):
295
+ chain.append(tag_line)
296
+ closed = True
297
+ break
298
+ if inline_branch.match(tag_line):
299
+ chain.append(tag_line)
300
+ continue
301
+ branch_body = single_line_body(cursor) if branch_tag.match(tag_line) else None
302
+ if branch_body is None:
303
+ break
304
+ chain.append(f"{tag_line} {branch_body}")
305
+ cursor += 1
306
+ joined = " ".join(chain)
307
+ if closed and len(joined) <= line_length:
308
+ compacted_lines.append(joined)
309
+ index = cursor
310
+ elif len(first) <= line_length:
311
+ compacted_lines.append(first)
312
+ index += 2
313
+ else:
314
+ compacted_lines.append(line)
315
+ index += 1
316
+
317
+ return "\n".join(compacted_lines)
318
+
319
+
320
+ def _preserve_legacy_formatting(source_sql: str, formatted_sql: str, line_length: int) -> str:
321
+ """Apply compatibility shims for customer-visible Tinybird formatting.
322
+
323
+ These transformations intentionally preserve quirks from the sqlfmt 0.11
324
+ based CLI output. The dependency upgrade is for Python 3.14 compatibility;
325
+ it should not make customer projects fail `tb fmt --diff` because of style
326
+ churn unrelated to their code.
327
+ """
328
+ formatted_sql = _preserve_inline_jinja_blocks(source_sql, formatted_sql, line_length)
329
+ if re.search(r"\bas\s+end\b", source_sql, flags=re.IGNORECASE):
330
+ # When `end` is a column alias, 0.11 kept adjacent Jinja control tags
331
+ # on the same line instead of treating the alias as a CASE terminator.
332
+ formatted_sql = re.sub(r"(?m)^end\n(?=\{%\s*(?:else|end)\b)", "end ", formatted_sql)
333
+ lines = formatted_sql.splitlines()
334
+ # 0.11 attached a trailing comment on two AND terms to the first term;
335
+ # 0.28 attaches it to the last, mislabeling the condition in tb fmt output.
336
+ source_comments = {
337
+ line.split("--", 1)[1].strip(): line.strip()
338
+ for line in source_sql.splitlines()
339
+ if "--" in line and line.lstrip().lower().startswith("and ")
340
+ }
341
+ index = 1
342
+ while index < len(lines):
343
+ previous, current = lines[index - 1], lines[index]
344
+ if (
345
+ " --" in current
346
+ and current.lstrip().lower().startswith("and ")
347
+ and previous.lstrip().lower().startswith("and ")
348
+ ):
349
+ statement, comment = current.split(" --", 1)
350
+ source_line = source_comments.get(comment.strip(), "")
351
+ if source_line.lower().count(" and ") >= 1:
352
+ lines[index - 1] = f"{previous} --{comment}"
353
+ lines[index] = statement.rstrip()
354
+ previous, current = lines[index - 1], lines[index]
355
+ # 0.11 kept a following any(...) select item on the same line when
356
+ # space allowed; 0.28 always splits these qualified/long expressions.
357
+ if (
358
+ previous.endswith(",")
359
+ and ("." in previous or "(" in previous or len(previous.strip()) >= 26)
360
+ and not previous.lstrip().lower().startswith("any (")
361
+ and current.lstrip().lower().startswith("any (")
362
+ and len(previous) - len(previous.lstrip()) == len(current) - len(current.lstrip())
363
+ and len(previous) + 1 + len(current.strip()) <= line_length
364
+ ):
365
+ lines[index - 1] = f"{previous} {current.strip()}"
366
+ lines.pop(index)
367
+ else:
368
+ index += 1
369
+ return "\n".join(lines)
370
+
371
+
162
372
  class TinybirdDialect(ClickHouse):
163
373
  """
164
374
  This is an extension of the base rules.
@@ -174,63 +384,70 @@ class TinybirdDialect(ClickHouse):
174
384
  super().__init__()
175
385
  self.lower_keywords = lower_keywords
176
386
 
177
- override_rules = {
178
- "main": [
179
- Rule(
180
- name="quoted_name",
181
- priority=200,
182
- pattern=group(
183
- # tripled single quotes (optionally raw/bytes)
184
- r"(rb?|b|br)?'''.*?'''",
185
- # tripled double quotes
186
- r'(rb?|b|br)?""".*?"""',
187
- # possibly escaped double quotes
188
- r'(rb?|b|br|u&|@)?"([^"\\]*(\\.[^"\\]*|""[^"\\]*)*)"',
189
- # possibly escaped single quotes
190
- r"(rb?|b|br|u&|x)?'([^'\\]*(\\.[^'\\]*|''[^'\\]*)*)'",
191
- r"\$\w*\$[^$]*?\$\w*\$", # pg dollar-delimited strings
192
- # possibly escaped backtick
193
- r"`([^`\\]*(\\.[^`\\]*)*)`",
194
- r"((?<!\\)\$[\w$]+)", # Words starting with $ for .incl files
195
- ),
196
- action=partial(actions.add_node_to_buffer, token_type=TokenType.QUOTED_NAME),
197
- ),
198
- Rule(
199
- name="number",
200
- priority=700,
201
- pattern=group(
202
- r"-?0x[0-9a-f][0-9a-f_]*(\.[0-9a-f_]*)?(p[+-]?\d[\d_]*)?",
203
- r"-?0b[01][01_]*",
204
- r"-?(\d[\d_]*\.?[\d_]*|\.\d[\d_]*)(e[+-]?\d[\d_]*)?",
205
- ),
206
- action=partial(actions.add_node_to_buffer, token_type=TokenType.NUMBER),
207
- ),
208
- ],
209
- "jinja": [
210
- Rule(
211
- name="jinja_if_block_end",
212
- priority=203,
213
- # Accept both Tornado-style {% end %} and {% end if %}
214
- pattern=group(r"\{%-?\s*end(\s+if)?\s*-?%\}"),
215
- action=actions.raise_sqlfmt_bracket_error,
387
+ override_rules = [
388
+ Rule(
389
+ name="number",
390
+ priority=401,
391
+ pattern=group(
392
+ r"-?0x[0-9a-f][0-9a-f_]*(\.[0-9a-f_]*)?(p[+-]?\d[\d_]*)?",
393
+ r"-?0b[01][01_]*",
394
+ r"-?(\d[\d_]*\.?[\d_]*|\.\d[\d_]*)(e[+-]?\d[\d_]*)?",
216
395
  ),
217
- Rule(
218
- name="jinja_for_block_end",
219
- priority=211,
220
- # Accept both Tornado-style {% end %} and {% end for %}
221
- pattern=group(r"\{%-?\s*end(\s+for)?\s*-?%\}"),
222
- action=actions.raise_sqlfmt_bracket_error,
396
+ action=partial(actions.add_node_to_buffer, token_type=TokenType.NUMBER),
397
+ ),
398
+ Rule(
399
+ name="quoted_name",
400
+ priority=200,
401
+ pattern=group(
402
+ SQL_QUOTED_EXP,
403
+ r"((?<!\\)\$[\w$]+)", # Words starting with $ for .incl files
223
404
  ),
224
- ],
225
- }
226
-
227
- for section, rules in override_rules.items():
228
- for rule in rules:
229
- for rr in self.RULES[section]:
230
- if rr.name == rule.name:
231
- self.RULES[section].remove(rr)
232
- self.RULES[section].append(rule)
233
- break
405
+ action=partial(actions.add_node_to_buffer, token_type=TokenType.QUOTED_NAME),
406
+ ),
407
+ Rule(
408
+ name="legacy_array_join",
409
+ priority=1040,
410
+ # 0.11 parsed ARRAY and JOIN separately, so wrapped joins keep
411
+ # ARRAY at the end of the preceding line.
412
+ pattern=group(r"array(?=\s+join\b)"),
413
+ action=partial(actions.add_node_to_buffer, token_type=TokenType.NAME),
414
+ ),
415
+ Rule(
416
+ name="join_using",
417
+ priority=1049,
418
+ # sqlfmt 0.11 treats USING without parentheses as a word operator.
419
+ pattern=group(r"using") + group(r"\W", r"$"),
420
+ action=partial(actions.add_node_to_buffer, token_type=TokenType.WORD_OPERATOR),
421
+ ),
422
+ Rule(
423
+ name="legacy_any_operator",
424
+ priority=1098,
425
+ # 0.11 classified any(...) as an operator and printed any (...).
426
+ pattern=group(r"any") + group(r"\W", r"$"),
427
+ action=partial(actions.add_node_to_buffer, token_type=TokenType.WORD_OPERATOR),
428
+ ),
429
+ Rule(
430
+ name="jinja_if_block_end",
431
+ priority=203,
432
+ # Accept both Tornado-style {% end %} and {% end if %}.
433
+ pattern=group(r"\{%-?\s*end(\s+if)?\s*-?%\}"),
434
+ action=actions.handle_jinja_block_end,
435
+ ),
436
+ Rule(
437
+ name="jinja_for_block_end",
438
+ priority=211,
439
+ # Accept both Tornado-style {% end %} and {% end for %}.
440
+ pattern=group(r"\{%-?\s*end(\s+for)?\s*-?%\}"),
441
+ action=actions.handle_jinja_block_end,
442
+ ),
443
+ ]
444
+
445
+ override_rules_by_name = {rule.name: rule for rule in override_rules}
446
+ self.RULES = _replace_rules(self.RULES, override_rules_by_name)
447
+ # Unlike USING, these are extra legacy tokens absent from 0.28's
448
+ # ruleset; register them so old projects keep their formatted output.
449
+ self.RULES.insert(0, override_rules_by_name["legacy_any_operator"])
450
+ self.RULES.insert(0, override_rules_by_name["legacy_array_join"])
234
451
 
235
452
  def initialize_analyzer(self, line_length: int) -> Analyzer:
236
453
  """
@@ -265,7 +482,7 @@ def _calc_str(self) -> str:
265
482
  return marker + " " + comment_text + "\n"
266
483
 
267
484
 
268
- Comment._calc_str = property(_calc_str)
485
+ Comment._calc_str = property(_calc_str) # type: ignore[attr-defined]
269
486
 
270
487
 
271
488
  def format_sql_template(
@@ -284,11 +501,12 @@ def format_sql_template(
284
501
 
285
502
  mode = TBMode(**config)
286
503
  sql = sql.strip()
287
- return (
504
+ formatted_sql = (
288
505
  "%\n" + api.format_string(sql[1:], mode=mode).strip()
289
506
  if sql[0] == "%"
290
507
  else api.format_string(sql, mode=mode).strip()
291
508
  )
509
+ return _preserve_legacy_formatting(sql, formatted_sql, mode.line_length)
292
510
  except Exception as e:
293
511
  resource_info = f" in '{resource_name}'" if resource_name else ""
294
512
  source_info = f" ({resource_source})" if resource_source else ""
tinybird/tb/__cli__.py CHANGED
@@ -4,5 +4,5 @@ __description__ = 'Tinybird Command Line Tool'
4
4
  __url__ = 'https://www.tinybird.co/docs/forward/commands'
5
5
  __author__ = 'Tinybird'
6
6
  __author_email__ = 'support@tinybird.co'
7
- __version__ = '5.0.3.dev0'
8
- __revision__ = '74fe6e30'
7
+ __version__ = '5.0.4.dev0'
8
+ __revision__ = 'ef090149'
@@ -17,7 +17,6 @@ from docker.client import DockerClient
17
17
  from docker.errors import ImageNotFound
18
18
  from docker.models.containers import Container
19
19
 
20
- import docker
21
20
  from tinybird.tb.client import AuthNoTokenException, TinyB
22
21
  from tinybird.tb.modules.config import CLIConfig
23
22
  from tinybird.tb.modules.exceptions import CLILocalException
@@ -683,7 +682,7 @@ def get_docker_client() -> DockerClient:
683
682
  except Exception:
684
683
  pass
685
684
  try:
686
- client = docker.from_env() # type: ignore
685
+ client = DockerClient.from_env()
687
686
  except Exception as e:
688
687
  add_telemetry_event(
689
688
  "docker_error",
@@ -197,7 +197,7 @@ if you need to include a literal ``{{``, ``{%``, or ``{#`` in the output.
197
197
 
198
198
  import ast
199
199
  import builtins
200
- import datetime
200
+ import datetime as dt
201
201
  import linecache
202
202
  import os.path
203
203
  import re
@@ -335,7 +335,7 @@ class Template:
335
335
  "json_encode": escape.json_encode,
336
336
  "squeeze": escape.squeeze,
337
337
  "linkify": escape.linkify,
338
- "datetime": datetime,
338
+ "datetime": dt,
339
339
  "_tt_utf8": escape.utf8, # for internal use
340
340
  "_tt_string_types": (unicode_type, bytes),
341
341
  # __name__ and __loader__ allow the traceback mechanism to find