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/ddl.py ADDED
@@ -0,0 +1,424 @@
1
+ """DDL layout: CREATE TABLE / CTAS / VIEW / MATERIALIZED VIEW,
2
+ TRUNCATE, CREATE INDEX, GRANT.
3
+
4
+ CREATE TABLE columns align name -> type -> constraints. Postgres keeps every
5
+ constraint (NOT NULL / DEFAULT) in one column after the type; Redshift, which
6
+ can carry both a nullability and an ENCODE on one column, splits them into a
7
+ nullability column and an ENCODE column (per-kind alignment, ). All
8
+ column alignment is resolver-tagged (the fixpoint pass composes the dependent
9
+ name/type/constraint columns); no manual padding.
10
+
11
+ CTAS / CREATE [MATERIALIZED] VIEW render a `CREATE ... AS` header line then
12
+ reuse `layout_statement` for the SELECT body. TRUNCATE / CREATE INDEX / GRANT
13
+ are utility one-liners (INDEX breaks its partial `WHERE` when over width;
14
+ TRUNCATE drops its RESTART/CASCADE options to a second line).
15
+ """
16
+ from sqlglot import exp
17
+
18
+ from sqlalign.casing import render_expr
19
+ from sqlalign.commas import COMMA_KIND
20
+ from sqlalign.ir import Line, Seg
21
+ from sqlalign.layout import Unsupported, guard_args, layout_statement
22
+
23
+ _CREATE_TABLE_OK = {"this", "kind", "expression", "properties", "replace", "exists"}
24
+ _ALTER_OK = {"this", "kind", "actions", "exists", "only"}
25
+
26
+
27
+ def ddl_lines(node, dialect, width, anchor=0):
28
+ if isinstance(node, exp.Create):
29
+ return _create_lines(node, dialect, width, anchor)
30
+ if isinstance(node, exp.TruncateTable):
31
+ return _truncate_lines(node, dialect, anchor)
32
+ if isinstance(node, (exp.Grant, exp.Command)):
33
+ return _grant_lines(node, dialect, anchor)
34
+ if isinstance(node, exp.Alter):
35
+ return _alter_lines(node, dialect, anchor)
36
+ if isinstance(node, exp.Drop):
37
+ return _one_line(node, dialect, anchor)
38
+ if isinstance(node, exp.Comment):
39
+ return _comment_lines(node, dialect, anchor)
40
+ if isinstance(node, exp.Declare):
41
+ return _declare_lines(node, dialect, anchor)
42
+ if isinstance(node, exp.Copy):
43
+ # Redshift's bulk loader. One line, spelled by sqlglot, which uppercases
44
+ # the structural keywords. Its options (`csv gzip ignoreheader 1`) are
45
+ # bare Vars keeping the case the author wrote: casing them would need a
46
+ # `_CASEFOLD_VAR_ARGS` entry, which makes the AST check blind to that
47
+ # difference over a vocabulary far wider than this models.
48
+ return _one_line(node, dialect, anchor)
49
+ raise Unsupported(type(node).__name__)
50
+
51
+
52
+ # ---- CREATE dispatch -------------------------------------------------------
53
+
54
+ def _create_lines(node, dialect, width, anchor):
55
+ kind = (node.args.get("kind") or "").upper()
56
+ if kind == "INDEX":
57
+ return _create_index_lines(node, dialect, width, anchor)
58
+ if kind == "VIEW":
59
+ return _create_as_lines(node, dialect, width, anchor)
60
+ if kind == "TABLE":
61
+ if node.args.get("expression") is not None: # CREATE TABLE ... AS SELECT
62
+ return _create_as_lines(node, dialect, width, anchor)
63
+ return _create_table_lines(node, dialect, width, anchor)
64
+ if kind == "PROCEDURE" and dialect == "tsql":
65
+ return _create_procedure_lines(node, dialect, width, anchor)
66
+ if kind == "SCHEMA":
67
+ return _one_line(node, dialect, anchor)
68
+ raise Unsupported(f"CREATE {kind}")
69
+
70
+
71
+ _PROCEDURE_OK = {"this", "kind", "expression", "begin"}
72
+
73
+
74
+ def _create_procedure_lines(node, dialect, width, anchor):
75
+ """T-SQL `CREATE PROCEDURE name [params] AS BEGIN ... END`.
76
+
77
+ Styled by analogy with a plpgsql `$$` body: the block's statements sit at column 1
78
+ with no extra indent, separated by blank lines, between `BEGIN` and `END;`
79
+ alone on their own lines. T-SQL's BEGIN/END is the structural counterpart of
80
+ the dollar-quoted body, so it inherits that geometry rather than inventing one.
81
+ """
82
+ guard_args(node, _PROCEDURE_OK, "CREATE PROCEDURE")
83
+ block = node.args.get("expression")
84
+ if block is None or type(block).__name__ != "Block":
85
+ raise Unsupported("CREATE PROCEDURE without a BEGIN...END block")
86
+
87
+ # sqlglot does not parse T-SQL control flow. Where an `IF` or `WHILE`
88
+ # appears, part of the body comes back as `exp.Command` holding raw source
89
+ # text: for an IF/ELSE, the entire ELSE branch. An `IfBlock` with an ELSE
90
+ # is indistinguishable from one without, so laying out the tree would drop
91
+ # it silently. Detected by looking for the unparsed remainder rather than by
92
+ # listing node types, so it lifts itself if sqlglot ever parses these.
93
+ if any(isinstance(n, exp.Command) for n in block.walk()):
94
+ raise Unsupported("CREATE PROCEDURE: sqlglot left part of the body unparsed")
95
+
96
+ lines = [
97
+ Line(anchor, [Seg(f"CREATE PROCEDURE {render_expr(node.this, dialect)}")]),
98
+ Line(anchor, [Seg("AS")]),
99
+ Line(anchor, [Seg("BEGIN")]),
100
+ Line(anchor, []),
101
+ ]
102
+ for statement in block.expressions:
103
+ if type(statement).__name__ == "EndStatement": # the block's own END
104
+ continue
105
+ body = layout_statement(statement, dialect, width, anchor)
106
+ body[-1].segs[-1].text += ";" # each body statement terminates
107
+ lines += body
108
+ lines.append(Line(anchor, []))
109
+ lines.append(Line(anchor, [Seg("END;")]))
110
+ return lines
111
+
112
+
113
+ def _create_as_lines(node, dialect, width, anchor):
114
+ """CTAS / CREATE [OR REPLACE] [MATERIALIZED] VIEW name AS <select>."""
115
+ kind = node.args.get("kind").upper()
116
+ parts = ["CREATE"]
117
+ if node.args.get("replace"):
118
+ parts.append("OR REPLACE")
119
+ if _has_property(node, exp.MaterializedProperty):
120
+ parts.append("MATERIALIZED")
121
+ parts.append(kind)
122
+ parts.append(render_expr(node.this, dialect)) # name (Schema/Table)
123
+ parts.append("AS")
124
+ header = Line(anchor, [Seg(" ".join(parts))])
125
+ body = node.args.get("expression")
126
+ lines = [header, *layout_statement(body, dialect, width, anchor)]
127
+
128
+ # `WITH DATA` / `WITH NO DATA` closes a CTAS, and `WITH NO DATA` creates an
129
+ # empty table. Any other property declines rather than being dropped.
130
+ for prop in _properties(node):
131
+ if isinstance(prop, exp.WithDataProperty):
132
+ lines.append(Line(anchor, [Seg("WITH NO DATA" if prop.args.get("no")
133
+ else "WITH DATA")]))
134
+ elif not isinstance(prop, exp.MaterializedProperty):
135
+ # Anything else would go the same silent way, so say so instead.
136
+ raise Unsupported(f"CREATE ... AS property: {type(prop).__name__}")
137
+ return lines
138
+
139
+
140
+ def _properties(node):
141
+ props = node.args.get("properties")
142
+ return props.expressions if props is not None else []
143
+
144
+
145
+ def _has_property(node, prop_type):
146
+ return any(isinstance(p, prop_type) for p in _properties(node))
147
+
148
+
149
+ # ---- CREATE TABLE ----------------------------------------------------------
150
+
151
+ def _create_table_lines(node, dialect, width, anchor):
152
+ guard_args(node, _CREATE_TABLE_OK, "CREATE TABLE")
153
+ schema = node.this # exp.Schema
154
+ if not isinstance(schema, exp.Schema):
155
+ # `CREATE TABLE t PARTITION OF p FOR VALUES IN (1)`: a partition
156
+ # declares no columns of its own; it inherits the parent's. There is no
157
+ # column list to align, so it is a one-liner spelled by sqlglot, whose
158
+ # `properties` carry the PARTITION OF and the bound.
159
+ if _has_property(node, exp.PartitionedOfProperty):
160
+ return _one_line(node, dialect, anchor)
161
+ raise Unsupported("CREATE TABLE without column list")
162
+ table = render_expr(schema.this, dialect)
163
+ defs = schema.expressions
164
+ encode_mode = any(_has_encode(d) for d in defs if isinstance(d, exp.ColumnDef))
165
+
166
+ lines = [Line(anchor, [Seg(f"CREATE TABLE {table} (")])]
167
+ scope = f"ddlcol@{id(node)}"
168
+ for i, d in enumerate(defs):
169
+ # render() adds one separator space after `head`, so 3-char heads put
170
+ # the column name at anchor+4: first line 3 spaces; else ` ,` (leading
171
+ # comma at anchor+2).
172
+ head = Seg(" " * 3) if i == 0 else Seg(" ,", kind=COMMA_KIND)
173
+ if isinstance(d, exp.ColumnDef):
174
+ lines.append(Line(anchor, [head, *_column_segs(d, scope, encode_mode, dialect)]))
175
+ else: # table-level constraint (PRIMARY KEY, ...)
176
+ lines.append(Line(anchor, [head, Seg(render_expr(d, dialect))]))
177
+ lines.append(Line(anchor, [Seg(")")]))
178
+ lines += _table_attributes(node, dialect, anchor)
179
+ return lines
180
+
181
+
182
+ def _column_segs(col, scope, encode_mode, dialect):
183
+ name = render_expr(col.this, dialect)
184
+ type_text = render_expr(col.args["kind"], dialect)
185
+ segs = [Seg(name), Seg(type_text, scope=scope, kind="type")]
186
+ if encode_mode:
187
+ nul, enc = _split_redshift_constraints(col, dialect)
188
+ if nul:
189
+ segs.append(Seg(nul, scope=scope, kind="nul"))
190
+ if enc:
191
+ segs.append(Seg(enc, scope=scope, kind="enc"))
192
+ else:
193
+ text = " ".join(render_expr(c, dialect) for c in col.args.get("constraints", []))
194
+ if text:
195
+ segs.append(Seg(text, scope=scope, kind="constraint"))
196
+ return segs
197
+
198
+
199
+ def _has_encode(col):
200
+ return any(isinstance(c.args.get("kind"), exp.EncodeColumnConstraint)
201
+ for c in col.args.get("constraints", []))
202
+
203
+
204
+ def _split_redshift_constraints(col, dialect):
205
+ """Redshift's two constraint columns: (nullability, ENCODE)."""
206
+ nul, enc = "", ""
207
+ for c in col.args.get("constraints", []):
208
+ k = c.args.get("kind")
209
+ if isinstance(k, exp.NotNullColumnConstraint):
210
+ nul = "NULL" if k.args.get("allow_null") else "NOT NULL"
211
+ elif isinstance(k, exp.EncodeColumnConstraint):
212
+ enc = render_expr(c, dialect)
213
+ else:
214
+ raise Unsupported(f"redshift column constraint: {type(k).__name__}")
215
+ return nul, enc
216
+
217
+
218
+ def _table_attributes(node, dialect, anchor):
219
+ """Redshift table attributes after the closing paren: DISTSTYLE + DISTKEY
220
+ share one line, SORTKEY takes the next."""
221
+ props = node.args.get("properties")
222
+ if props is None:
223
+ return []
224
+ diststyle = distkey = sortkey = None
225
+ for p in props.expressions:
226
+ if isinstance(p, exp.DistStyleProperty):
227
+ diststyle = "DISTSTYLE " + str(p.this).upper()
228
+ elif isinstance(p, exp.DistKeyProperty):
229
+ distkey = _space_before_paren(render_expr(p, dialect))
230
+ elif isinstance(p, exp.SortKeyProperty):
231
+ sortkey = _space_before_paren(render_expr(p, dialect))
232
+ else:
233
+ raise Unsupported(f"table property: {type(p).__name__}")
234
+ lines = []
235
+ if diststyle or distkey:
236
+ lines.append(Line(anchor, [Seg(" ".join(x for x in (diststyle, distkey) if x))]))
237
+ if sortkey:
238
+ lines.append(Line(anchor, [Seg(sortkey)]))
239
+ return lines
240
+
241
+
242
+ def _space_before_paren(text, after=""):
243
+ """Insert the house space between a keyword and its `(` — `DISTKEY (col)`,
244
+ `SORTKEY (col)`, `ON orders (col)`, which the generator emits tight.
245
+
246
+ `after` restricts the fix to the first `(` past that marker, so a paren
247
+ earlier in the text (a CREATE INDEX name, say) is left alone.
248
+ """
249
+ start = text.find(after) if after else 0
250
+ if start == -1:
251
+ return text
252
+ i = text.find("(", start)
253
+ return text if i <= 0 or text[i - 1] == " " else text[:i] + " " + text[i:]
254
+
255
+
256
+ # ---- TRUNCATE / INDEX / GRANT ---------------------------------------------
257
+
258
+ def _truncate_lines(node, dialect, anchor):
259
+ tables = ", ".join(render_expr(t, dialect) for t in node.args["expressions"])
260
+ lines = [Line(anchor, [Seg(f"TRUNCATE TABLE {tables}")])]
261
+ opts = []
262
+ identity = node.args.get("identity")
263
+ if identity:
264
+ opts.append(f"{identity.upper()} IDENTITY")
265
+ option = node.args.get("option")
266
+ if option:
267
+ opts.append(option.upper())
268
+ if opts:
269
+ lines.append(Line(anchor, [Seg(" ".join(opts))]))
270
+ return lines
271
+
272
+
273
+ def _create_index_lines(node, dialect, width, anchor):
274
+ text = render_expr(node, dialect)
275
+ # Restore the house space between the indexed table and its column list
276
+ # (`ON orders (cols)`), which the generator emits tight, and split off a
277
+ # trailing partial-index WHERE so it can drop to its own line.
278
+ where_idx = text.find(" WHERE ")
279
+ head, where = (text[:where_idx], text[where_idx + 1:]) if where_idx != -1 else (text, "")
280
+ head = _space_before_paren(head, " ON ")
281
+ lines = [Line(anchor, [Seg(head)])]
282
+ if where and (len(head) > width.width or len(f"{head} {where}") > width.limit(anchor)):
283
+ lines.append(Line(anchor, [Seg(where)]))
284
+ elif where:
285
+ lines[0] = Line(anchor, [Seg(f"{head} {where}")])
286
+ return lines
287
+
288
+
289
+ def _grant_lines(node, dialect, anchor):
290
+ if isinstance(node, exp.Command):
291
+ return [Line(anchor, [Seg(_uppercase_keywords(node, dialect))])]
292
+ return [Line(anchor, [Seg(render_expr(node, dialect))])]
293
+
294
+
295
+ # Keywords that appear in a GRANT ... ON ALL <objs> IN SCHEMA ... TO ...
296
+ # statement but that sqlglot's tokenizer does not list as single-word keywords
297
+ # (it has TABLE, not TABLES; no TO). Best-effort supplement for the Command path.
298
+ _GRANT_KEYWORDS = {"TO", "TABLES", "SEQUENCES", "FUNCTIONS", "PROCEDURES", "ROUTINES"}
299
+
300
+
301
+ def _uppercase_keywords(command, dialect):
302
+ """Best-effort keyword uppercasing for a GRANT that sqlglot could only
303
+ parse as an unsupported-syntax `Command` (e.g. `GRANT ... ON ALL TABLES IN
304
+ SCHEMA ...`): uppercase every whitespace-separated word that is a known SQL
305
+ keyword, preserve identifiers. ast_equal casefolds Command text, so this is
306
+ safety-net-neutral."""
307
+ from sqlglot.tokens import Tokenizer
308
+ keywords = {kw for kw in Tokenizer(dialect=dialect).KEYWORDS if " " not in kw}
309
+ keywords |= _GRANT_KEYWORDS
310
+ raw = f"{command.this} {command.args.get('expression', '')}"
311
+ return " ".join(w.upper() if w.upper() in keywords else w for w in raw.split())
312
+
313
+
314
+ # ---- ALTER -----------------------------------------------------------------
315
+
316
+ def _alter_lines(node, dialect, anchor):
317
+ """`ALTER TABLE t ADD COLUMN c INT` and its relatives.
318
+
319
+ One action rides the head line; two or more stack under it in the house's
320
+ leading-comma list, at the same item/comma columns a CREATE TABLE column
321
+ list uses. There is no list with one item, which is the whole reason for the
322
+ split: a lone action has no column to hold.
323
+
324
+ Each action's text is DERIVED, by rendering an ALTER that carries only that
325
+ action and removing the head. A bare `ColumnDef` renders as `c INT`: the
326
+ `ADD COLUMN` prefix lives in sqlglot's ALTER generator, not on the node, and
327
+ the action vocabulary is wide enough (ADD COLUMN, DROP, RENAME TO, ALTER
328
+ COLUMN ... SET/DROP, ADD CONSTRAINT, ...) that a prefix table here would
329
+ fall behind. The head is computed and then CHECKED against what sqlglot
330
+ actually produced, so a spelling this does not predict declines instead of
331
+ being silently mangled.
332
+
333
+ `kind` is None when sqlglot could not parse the action at all (`ALTER TABLE
334
+ t OWNER TO bob` falls back to a Command), which `guard_args` cannot catch
335
+ because the arg is simply absent.
336
+ """
337
+ guard_args(node, _ALTER_OK, label="ALTER")
338
+ kind = node.args.get("kind")
339
+ actions = node.args.get("actions") or []
340
+ if not kind or not actions:
341
+ raise Unsupported("ALTER: unparsed action")
342
+
343
+ exists = " IF EXISTS" if node.args.get("exists") else ""
344
+ only = " ONLY" if node.args.get("only") else ""
345
+ head = f"ALTER {kind.upper()}{exists}{only} {render_expr(node.this, dialect)}"
346
+
347
+ tails = []
348
+ for action in actions:
349
+ one = node.copy()
350
+ one.set("actions", [action])
351
+ whole = render_expr(one, dialect)
352
+ if not whole.startswith(head + " "):
353
+ raise Unsupported("ALTER: unexpected head spelling")
354
+ tails.append(whole[len(head) + 1:])
355
+
356
+ if len(tails) == 1:
357
+ return [Line(anchor, [Seg(head), Seg(tails[0])])]
358
+
359
+ lines = [Line(anchor, [Seg(head)])]
360
+ for i, tail in enumerate(tails):
361
+ if i == 0:
362
+ lines.append(Line(anchor + 4, [Seg(tail)]))
363
+ else:
364
+ lines.append(Line(anchor + 2, [Seg(",", kind=COMMA_KIND), Seg(tail)]))
365
+ return lines
366
+
367
+
368
+ # ---- one-line utility statements -------------------------------------------
369
+
370
+ def _one_line(node, dialect, anchor):
371
+ """A statement with no internal structure to align: `DROP TABLE IF EXISTS t
372
+ CASCADE`, `CREATE SCHEMA s`. sqlglot's generator spells the whole thing, and
373
+ there is nothing here for the resolver to hold a column for: laying it out
374
+ by hand would only be a chance to get a keyword wrong.
375
+ """
376
+ return [Line(anchor, [Seg(render_expr(node, dialect))])]
377
+
378
+
379
+ def _comment_lines(node, dialect, anchor):
380
+ """`COMMENT ON TABLE t IS 'x'`.
381
+
382
+ Not `_one_line`, because sqlglot echoes the object kind in whatever case it
383
+ was WRITTEN in: `comment on table t` renders `COMMENT ON table t`, with a
384
+ keyword left lowercase in the middle of an uppercased statement. The kind is
385
+ a keyword like any other, so it is cased here before rendering.
386
+ """
387
+ kind = node.args.get("kind")
388
+ if isinstance(kind, str):
389
+ node = node.copy()
390
+ node.set("kind", kind.upper())
391
+ return [Line(anchor, [Seg(render_expr(node, dialect))])]
392
+
393
+
394
+ def _declare_lines(node, dialect, anchor):
395
+ """T-SQL `DECLARE @x INT = 5`.
396
+
397
+ One declaration rides the head line; several stack in the house's
398
+ leading-comma list, the same split `_alter_lines` makes for the same reason
399
+ , there is no list with one item.
400
+
401
+ Each declaration's text is DERIVED, by rendering a DECLARE that carries only
402
+ it and removing the head, so the spelling of a type or a default is
403
+ sqlglot's rather than reconstructed here.
404
+ """
405
+ items = node.expressions
406
+ if not items:
407
+ raise Unsupported("DECLARE without declarations")
408
+ head = "DECLARE"
409
+ tails = []
410
+ for item in items:
411
+ one = node.copy()
412
+ one.set("expressions", [item])
413
+ whole = render_expr(one, dialect)
414
+ if not whole.startswith(head + " "):
415
+ raise Unsupported("DECLARE: unexpected head spelling")
416
+ tails.append(whole[len(head) + 1:])
417
+
418
+ if len(tails) == 1:
419
+ return [Line(anchor, [Seg(head), Seg(tails[0])])]
420
+ lines = [Line(anchor, [Seg(head)])]
421
+ for i, tail in enumerate(tails):
422
+ lines.append(Line(anchor + 4, [Seg(tail)]) if i == 0
423
+ else Line(anchor + 2, [Seg(",", kind=COMMA_KIND), Seg(tail)]))
424
+ return lines