sqlalign 1.0.1__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.
sqlalign/layout/dml.py ADDED
@@ -0,0 +1,287 @@
1
+ """DML layout: INSERT, UPDATE, DELETE, MERGE.
2
+
3
+ Each statement's clauses start at the anchor column. INSERT/MERGE column and
4
+ VALUES lists use the house paren-list shape (`( a` / ` , b`, items at
5
+ anchor+3, commas at anchor+1). UPDATE/MERGE `SET` assignments right-align `=`
6
+ (`kind="op"`) exactly like a WHERE comparison, with the assignment target at
7
+ anchor+4 (after `SET `) and leading commas at anchor+2. WHERE and the MERGE
8
+ `ON` block reuse `conditions.condition_block`; the SELECT inside an INSERT
9
+ reuses `layout_statement`.
10
+
11
+ Anything outside the modeled shape (ON CONFLICT, RETURNING, UPDATE...FROM,
12
+ DELETE...USING, a conditional `WHEN MATCHED AND ...`, ...) raises `Unsupported`
13
+ -> byte-identical passthrough, so the tool never half-renders a DML statement.
14
+ """
15
+ from sqlglot import exp
16
+
17
+ from sqlalign.casing import render_expr
18
+ from sqlalign.commas import COMMA_KIND
19
+ from sqlalign.ir import Line, Seg
20
+ from sqlalign.layout import (
21
+ Unsupported,
22
+ clause_head,
23
+ comma_clause,
24
+ guard_args,
25
+ layout_statement,
26
+ table_alias,
27
+ table_name,
28
+ )
29
+ from sqlalign.layout.conditions import condition_block
30
+
31
+ _INSERT_OK = {"this", "expression", "conflict", "returning", "default"}
32
+ _UPDATE_OK = {"this", "expressions", "where", "from_", "returning"}
33
+ _DELETE_OK = {"this", "where", "using", "returning"}
34
+ _MERGE_OK = {"this", "using", "on", "whens"}
35
+
36
+
37
+ def dml_lines(node, dialect, width, anchor=0):
38
+ if isinstance(node, exp.Insert):
39
+ return _insert_lines(node, dialect, width, anchor)
40
+ if isinstance(node, exp.Update):
41
+ return _update_lines(node, dialect, width, anchor)
42
+ if isinstance(node, exp.Delete):
43
+ return _delete_lines(node, dialect, width, anchor)
44
+ if isinstance(node, exp.Merge):
45
+ return _merge_lines(node, dialect, width, anchor)
46
+ raise Unsupported(type(node).__name__)
47
+
48
+
49
+ def values_lines(node, dialect, anchor):
50
+ """An INSERT's `VALUES` rows: one tuple per line, stacked with leading commas
51
+ two columns before the tuple: the same geometry the select list uses, and
52
+ `VALUES ` happens to be the same width as `SELECT `, so the commas land in
53
+ the house column without any special case.
54
+
55
+ VALUES (1, 'a')
56
+ , (2, 'b');
57
+
58
+ A single row stays inline. The tuples themselves are rendered as-is; their
59
+ contents are data, not a structure this layer models, so nothing inside a
60
+ tuple is aligned across rows.
61
+ """
62
+ guard_args(node, {"expressions"}, "VALUES")
63
+ rows = node.expressions
64
+ if not rows or not all(isinstance(r, exp.Tuple) for r in rows):
65
+ raise Unsupported("VALUES: unexpected row shape")
66
+ return comma_clause("VALUES", [render_expr(r, dialect) for r in rows], anchor)
67
+
68
+
69
+ def _verb_line(keyword, anchor, *rest):
70
+ """A DML verb's own line. Goes through `clause_head` so `UPDATE`/`SET`/
71
+ `WHERE` form a river together when one is asked for, instead of the verb
72
+ sitting flush left while its WHERE right-aligns."""
73
+ kw_anchor, kw_text = clause_head(keyword, anchor)
74
+ return Line(kw_anchor, [Seg(kw_text), *rest])
75
+
76
+
77
+ def _table_with_alias(table, dialect):
78
+ """`schema.name alias` — a table reference in UPDATE/DELETE/MERGE, with the
79
+ alias spelled per `Style.table_alias_style`."""
80
+ alias = table_alias(table, dialect)
81
+ name = table_name(table, dialect)
82
+ return name + " " + alias if alias is not None else name
83
+
84
+
85
+ def _paren_list(items_text, anchor, close_own_line):
86
+ """House column/VALUES list: `( first` / ` , next`, items at anchor+3.
87
+ `close_own_line` False tucks `)` after the last item (INSERT columns);
88
+ True drops `)` to its own line (a MERGE VALUES tuple)."""
89
+ lines = []
90
+ last = len(items_text) - 1
91
+ for i, text in enumerate(items_text):
92
+ # The head is its own Seg so the separator comma can be relocated by
93
+ # commas.py; render()'s automatic inter-seg space supplies the gap, so
94
+ # `Seg("( ")` + space = the house `( ` and `Seg(" ,")` + space = ` , `.
95
+ head = Seg("( ") if i == 0 else Seg(" ,", kind=COMMA_KIND)
96
+ segs = [head, Seg(text)]
97
+ if i == last and not close_own_line:
98
+ segs[-1].text += ")"
99
+ lines.append(Line(anchor, segs))
100
+ if close_own_line:
101
+ lines.append(Line(anchor, [Seg(")")]))
102
+ return lines
103
+
104
+
105
+ def _set_lines(eqs, anchor, scope, dialect):
106
+ """`SET target = value` assignments: target at anchor+4, leading commas at
107
+ anchor+2, `=` right-aligned across every assignment (`kind="op"`)."""
108
+ kw_anchor, kw_text = clause_head("SET", anchor)
109
+ # The comma keeps sitting two columns before the target, wherever SET put it.
110
+ comma_lead = " " * (kw_anchor + len(kw_text) + 1 - anchor - 2)
111
+ lines = []
112
+ for i, eq in enumerate(eqs):
113
+ head = Seg(kw_text) if i == 0 else Seg(comma_lead + ",", kind=COMMA_KIND)
114
+ lines.append(Line(kw_anchor if i == 0 else anchor, [
115
+ head,
116
+ Seg(render_expr(eq.this, dialect)),
117
+ Seg("=", scope=scope, kind="op"),
118
+ Seg(render_expr(eq.expression, dialect)),
119
+ ]))
120
+ return lines
121
+
122
+
123
+ def _insert_lines(node, dialect, width, anchor):
124
+ guard_args(node, _INSERT_OK)
125
+ this = node.this
126
+ if isinstance(this, exp.Schema):
127
+ table, cols = this.this, this.expressions
128
+ else:
129
+ table, cols = this, []
130
+ lines = [_verb_line("INSERT INTO", anchor, Seg(render_expr(table, dialect)))]
131
+ if cols:
132
+ lines += _paren_list([render_expr(c, dialect) for c in cols], anchor, close_own_line=False)
133
+ # `INSERT INTO t DEFAULT VALUES`: one row, every column its default. There
134
+ # is no body at all, which is why the body check below rejected it.
135
+ if node.args.get("default"):
136
+ lines.append(Line(anchor, [Seg("DEFAULT VALUES")]))
137
+ return lines + _returning_lines(node, dialect, anchor)
138
+ if _returning_first(dialect):
139
+ lines += _returning_lines(node, dialect, anchor)
140
+ body = node.expression
141
+ if body is None or not isinstance(body, (exp.Select, exp.SetOperation, exp.Values)):
142
+ raise Unsupported("INSERT body")
143
+ lines += layout_statement(body, dialect, width, anchor)
144
+ conflict = node.args.get("conflict")
145
+ if conflict is not None:
146
+ lines += _conflict_lines(conflict, dialect, anchor)
147
+ if _returning_first(dialect):
148
+ return lines
149
+ return lines + _returning_lines(node, dialect, anchor)
150
+
151
+
152
+ def _conflict_lines(conflict, dialect, anchor):
153
+ """`ON CONFLICT ... DO NOTHING` / `... DO UPDATE SET ...` (Postgres upsert).
154
+
155
+ ON CONFLICT (customer_id) DO UPDATE
156
+ SET email = EXCLUDED.email
157
+ , updated_at = NOW()
158
+
159
+ The assignments reuse the UPDATE geometry: the same `SET`/leading-comma
160
+ stack with the `=` column aligned — because they are the same construct in
161
+ the same statement, and having them differ would be a wart a reader notices
162
+ immediately.
163
+ """
164
+ guard_args(conflict, {"action", "conflict_keys", "constraint", "expressions", "where"},
165
+ "ON CONFLICT")
166
+ target = ""
167
+ if conflict.args.get("constraint") is not None:
168
+ target = f" ON CONSTRAINT {render_expr(conflict.args['constraint'], dialect)}"
169
+ elif conflict.args.get("conflict_keys"):
170
+ keys = ", ".join(render_expr(k, dialect) for k in conflict.args["conflict_keys"])
171
+ target = f" ({keys})"
172
+
173
+ action = conflict.args.get("action")
174
+ if action is None:
175
+ raise Unsupported("ON CONFLICT: no action")
176
+ action_text = render_expr(action, dialect).upper()
177
+
178
+ head = f"ON CONFLICT{target} {action_text}"
179
+ lines = [Line(anchor, [Seg(head)])]
180
+ assignments = conflict.args.get("expressions")
181
+ if assignments:
182
+ lines += _set_lines(assignments, anchor, f"conflict@{id(conflict)}", dialect)
183
+ where = conflict.args.get("where")
184
+ if where is not None:
185
+ lines += condition_block("WHERE", where.this, f"conflictwhere@{id(conflict)}",
186
+ anchor, dialect, None)
187
+ return lines
188
+
189
+
190
+ def _returning_lines(node, dialect, anchor):
191
+ """`RETURNING a, b` / `RETURNING *`, or T-SQL's `OUTPUT inserted.a`.
192
+
193
+ Rendered whole by sqlglot rather than rebuilt from its expressions, so `*`
194
+ and a column list spell themselves the same way they do anywhere else.
195
+
196
+ The two spellings share the `returning` arg but NOT their position, which is
197
+ why every caller asks `_returning_first` where to put it: Postgres closes the
198
+ statement with RETURNING, while T-SQL's OUTPUT comes BEFORE the body it
199
+ describes. Emitting it last under T-SQL produced `INSERT INTO t (a) SELECT …
200
+ OUTPUT inserted.a`, which SQL Server rejects, and `ast_equal` cannot see
201
+ it, because sqlglot reads its own lenient output back without complaint.
202
+ """
203
+ returning = node.args.get("returning")
204
+ if returning is None:
205
+ return []
206
+ return [Line(anchor, [Seg(render_expr(returning, dialect))])]
207
+
208
+
209
+ def _returning_first(dialect) -> bool:
210
+ """Whether the returning clause precedes the statement body."""
211
+ return dialect == "tsql"
212
+
213
+
214
+ def _update_lines(node, dialect, width, anchor):
215
+ guard_args(node, _UPDATE_OK)
216
+ lines = [_verb_line("UPDATE", anchor, Seg(_table_with_alias(node.this, dialect)))]
217
+ lines += _set_lines(node.expressions, anchor, f"set@{id(node)}", dialect)
218
+ if _returning_first(dialect):
219
+ lines += _returning_lines(node, dialect, anchor)
220
+ # `UPDATE t SET ... FROM u WHERE u.i = t.i`: Postgres's join-in-an-update,
221
+ # the same shape DELETE's USING has. It sits between SET and the WHERE that
222
+ # references it, which is also where it is written.
223
+ from_ = node.args.get("from_")
224
+ if from_ is not None:
225
+ lines.append(Line(anchor, [Seg("FROM"),
226
+ Seg(_table_with_alias(from_.this, dialect))]))
227
+ where = node.args.get("where")
228
+ if where is not None:
229
+ lines += condition_block("WHERE", where.this, f"where@{id(node)}", anchor, dialect, width)
230
+ if _returning_first(dialect):
231
+ return lines
232
+ return lines + _returning_lines(node, dialect, anchor)
233
+
234
+
235
+ def _delete_lines(node, dialect, width, anchor):
236
+ guard_args(node, _DELETE_OK)
237
+ lines = [_verb_line("DELETE FROM", anchor, Seg(_table_with_alias(node.this, dialect)))]
238
+ # `DELETE FROM t USING u WHERE ...`: Postgres's join-in-a-delete. It is one
239
+ # clause line of table references, the same shape MERGE's USING already had,
240
+ # and it sits between the verb and the WHERE that references it.
241
+ using = node.args.get("using")
242
+ if using:
243
+ refs = using if isinstance(using, list) else [using]
244
+ lines.append(Line(anchor, [Seg("USING"),
245
+ Seg(", ".join(_table_with_alias(r, dialect)
246
+ for r in refs))]))
247
+ where = node.args.get("where")
248
+ if where is not None:
249
+ lines += condition_block("WHERE", where.this, f"where@{id(node)}", anchor, dialect, width)
250
+ if _returning_first(dialect):
251
+ return lines
252
+ return lines + _returning_lines(node, dialect, anchor)
253
+
254
+
255
+ def _merge_lines(node, dialect, width, anchor):
256
+ guard_args(node, _MERGE_OK)
257
+ lines = [
258
+ _verb_line("MERGE INTO", anchor, Seg(_table_with_alias(node.this, dialect))),
259
+ Line(anchor, [Seg("USING"), Seg(_table_with_alias(node.args["using"], dialect))]),
260
+ ]
261
+ lines += condition_block("ON", node.args["on"], f"on@{id(node)}", anchor + 2, dialect, width)
262
+ for wh in node.args["whens"].expressions:
263
+ if wh.args.get("condition") is not None:
264
+ raise Unsupported("MERGE conditional WHEN")
265
+ keyword = "WHEN MATCHED" if wh.args.get("matched") else "WHEN NOT MATCHED"
266
+ lines.append(Line(anchor, [Seg(keyword)]))
267
+ then = wh.args.get("then")
268
+ if isinstance(then, exp.Update):
269
+ lines.append(Line(anchor, [Seg("THEN UPDATE")]))
270
+ lines += _set_lines(then.expressions, anchor, f"mset@{id(wh)}", dialect)
271
+ elif isinstance(then, exp.Insert):
272
+ lines.append(Line(anchor, [Seg("THEN INSERT")]))
273
+ cols = then.this.expressions if hasattr(then.this, "expressions") else []
274
+ lines += _paren_list([render_expr(c, dialect) for c in cols],
275
+ anchor, close_own_line=False)
276
+ lines.append(Line(anchor, [Seg("VALUES")]))
277
+ vals = then.expression.expressions
278
+ lines += _paren_list([render_expr(v, dialect) for v in vals],
279
+ anchor, close_own_line=True)
280
+ elif isinstance(then, exp.Var) and str(then.this).upper() == "DELETE":
281
+ # `WHEN MATCHED THEN DELETE`: the whole action is the keyword, and
282
+ # sqlglot keeps it as a Var carrying the case it was written in, so
283
+ # it needs casing here rather than a render (`THEN delete`).
284
+ lines.append(Line(anchor, [Seg("THEN DELETE")]))
285
+ else:
286
+ raise Unsupported("MERGE THEN " + type(then).__name__)
287
+ return lines
@@ -0,0 +1,119 @@
1
+ """Long nested-expression breaking
2
+
3
+ A select item whose value is a call chain wrapping a single breakable CASE
4
+ (sample 21: `COALESCE(SUM(CASE … END), 0.00) AS funding_amt`) and whose flat
5
+ one-line render exceeds the width limit breaks AT the CASE: the wrapper prefix
6
+ (`COALESCE(SUM(`) rides line 0 directly before `CASE`, the CASE lays out
7
+ long-form (reusing case.py's `long_form_case_lines`) at columns SHIFTED right by
8
+ the prefix, and the wrapper's closers (`), 0.00)`) tuck onto the END line, which
9
+ sits at CASE-col + 1.
10
+
11
+ The requirements are now only structural: exactly one CASE, not at the value root
12
+ (a root CASE is case.py's job), and a wrapper whose flat render splits cleanly
13
+ around the CASE's own flat render. The prefix/suffix are DERIVED from
14
+ `render_expr` (never hard-coded) by locating the CASE's rendered substring inside
15
+ the value's rendered form — so the tuck is guaranteed token-consistent with the
16
+ flat render. Anything else returns None and the item renders FLAT.
17
+
18
+ `END` sits one column right of `CASE`: `END` is three characters and `CASE` is
19
+ four, so the wrapper's closers -- glued straight onto it -- land in the column
20
+ immediately after the CASE keyword, where the CASE's own content starts on line
21
+ 0:
22
+
23
+ , COALESCE(SUM(CASE WHEN … , MAX(CASE WHEN …
24
+ AND … AND …
25
+ THEN … THEN …
26
+ END), 0.00) END) AS …
27
+
28
+ That is a function of the two keywords' widths, so it holds for any prefix.
29
+ """
30
+ from sqlglot import exp
31
+
32
+ from sqlalign.casing import render_expr
33
+ from sqlalign.layout import column_alias, select_item_col
34
+ from sqlalign.layout.case import long_form_case_lines
35
+
36
+ _WHEN_OFFSET = len("CASE ") # 5: WHEN sits one space after CASE (long form)
37
+
38
+ # Where `END` sits, relative to the CASE column. Not an arbitrary indent: `END`
39
+ # is three characters and `CASE` is four, so this puts the wrapper's closers --
40
+ # glued straight onto END: in the column immediately after the CASE keyword,
41
+ # which is where the CASE's own content starts on line 0. Read off sample 21's
42
+ # bytes, where it is the only relationship that holds.
43
+ _END_OFFSET = len("CASE") - len("END") # 1
44
+
45
+
46
+ def nested_break_case(item, anchor, dialect, width):
47
+ """The CASE node this item breaks at, or None if `item` is not an
48
+ over-width nested-CASE-break shape. Pure predicate (no layout): select.py
49
+ uses it both to route the item here and to exempt the wrapped CASE from its
50
+ `_UNSUPPORTED_NODES` guard (a nested CASE is otherwise declined)."""
51
+ value = item.this if isinstance(item, exp.Alias) else item
52
+ matched = _match(value, dialect)
53
+ if matched is None:
54
+ return None
55
+ _prefix, case_node, _suffix = matched
56
+ if not _case_ok(case_node):
57
+ return None
58
+ if not _over_width(item, value, anchor, dialect, width):
59
+ return None
60
+ return case_node
61
+
62
+
63
+ def nested_break_body(item, anchor, dialect, width):
64
+ """The item's CASE-broken `list[Line]` (line 0's indent == `anchor`, ready
65
+ for select.py's `_multiline_item_lines` to splice the leading comma onto
66
+ line 0 and tuck `AS alias` onto the END line), or None if `item` is not the
67
+ recognized shape."""
68
+ if nested_break_case(item, anchor, dialect, width) is None:
69
+ return None
70
+ value = item.this if isinstance(item, exp.Alias) else item
71
+ prefix, case_node, suffix = _match(value, dialect)
72
+ item_col = select_item_col(anchor)
73
+ case_col = item_col + len(prefix)
74
+ # The simple form's test operand rides line 0 with CASE and pushes the WHEN
75
+ # column right by its width, exactly as it does for a root CASE (case.py).
76
+ operand = case_node.args.get("this")
77
+ head_text = "CASE" if operand is None else f"CASE {render_expr(operand, dialect)}"
78
+ when_col = case_col + len(head_text) + 1
79
+ return long_form_case_lines(
80
+ case_node, case_node.args["ifs"], case_node.args.get("default"), anchor,
81
+ when_col, dialect,
82
+ head=prefix + head_text, end_indent=case_col + _END_OFFSET, end_suffix=suffix,
83
+ )
84
+
85
+
86
+ def _match(value, dialect):
87
+ """Locate the single wrapped CASE and split the value's flat render around
88
+ it: `(prefix, case_node, suffix)`, or None. `prefix`/`suffix` are the exact
89
+ rendered text before/after the CASE (e.g. `COALESCE(SUM(` / `), 0.00)`), so
90
+ they compose byte-for-byte with the flat render every other item uses."""
91
+ cases = [n for n in value.walk() if isinstance(n, exp.Case)]
92
+ if len(cases) != 1:
93
+ return None
94
+ case_node = cases[0]
95
+ if case_node is value: # a root CASE belongs to case.py
96
+ return None
97
+ flat_value = render_expr(value, dialect)
98
+ flat_case = render_expr(case_node, dialect)
99
+ idx = flat_value.find(flat_case)
100
+ if idx < 0 or flat_value.find(flat_case, idx + 1) != -1:
101
+ return None # not found, or ambiguous
102
+ return flat_value[:idx], case_node, flat_value[idx + len(flat_case):]
103
+
104
+
105
+ def _case_ok(case_node):
106
+ """Every CASE is modelled here now -- see this module's docstring on why the
107
+ wrapper restriction lifted. A CASE with no WHENs cannot be parsed, so the
108
+ only thing left to check is that there is something to lay out."""
109
+ return bool(case_node.args.get("ifs"))
110
+
111
+
112
+ def _over_width(item, value, anchor, dialect, width):
113
+ """Whether the item's flat one-line render (leading comma column through the
114
+ alias) exceeds the width limit — the trigger to break at the CASE."""
115
+ flat = render_expr(value, dialect)
116
+ end = select_item_col(anchor) + len(flat)
117
+ if isinstance(item, exp.Alias):
118
+ end += 1 + len("AS " + column_alias(item, dialect))
119
+ return end > width.limit(anchor)