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/__init__.py +10 -0
- sqlalign/align.py +145 -0
- sqlalign/bodylint.py +125 -0
- sqlalign/casing.py +182 -0
- sqlalign/cli.py +360 -0
- sqlalign/commas.py +58 -0
- sqlalign/config.py +28 -0
- sqlalign/configfile.py +194 -0
- sqlalign/formatter.py +609 -0
- sqlalign/gui.py +721 -0
- sqlalign/ir.py +38 -0
- sqlalign/keywordcase.py +127 -0
- sqlalign/layout/__init__.py +312 -0
- sqlalign/layout/case.py +222 -0
- sqlalign/layout/comments.py +530 -0
- sqlalign/layout/conditions.py +344 -0
- sqlalign/layout/cte.py +81 -0
- sqlalign/layout/ddl.py +424 -0
- sqlalign/layout/dml.py +287 -0
- sqlalign/layout/expr.py +119 -0
- sqlalign/layout/fromjoin.py +310 -0
- sqlalign/layout/grouporder.py +135 -0
- sqlalign/layout/select.py +523 -0
- sqlalign/layout/setop.py +78 -0
- sqlalign/layout/subquery.py +245 -0
- sqlalign/layout/window.py +207 -0
- sqlalign/lint.py +173 -0
- sqlalign/plpgsql.py +437 -0
- sqlalign/splitter.py +241 -0
- sqlalign/sqlfluffconfig.py +88 -0
- sqlalign/style.py +215 -0
- sqlalign/templating.py +87 -0
- sqlalign-1.0.1.dist-info/METADATA +404 -0
- sqlalign-1.0.1.dist-info/RECORD +37 -0
- sqlalign-1.0.1.dist-info/WHEEL +4 -0
- sqlalign-1.0.1.dist-info/entry_points.txt +2 -0
- sqlalign-1.0.1.dist-info/licenses/LICENSE +21 -0
|
@@ -0,0 +1,88 @@
|
|
|
1
|
+
"""Generate the sqlfluff config that lets sqlfluff run alongside sqlalign.
|
|
2
|
+
|
|
3
|
+
The two tools overlap, and left to themselves they fight: `sqlfluff fix` would
|
|
4
|
+
undo the columnar alignment on every run. The resolution is the one Prettier and
|
|
5
|
+
`eslint-config-prettier` settled on years ago: **the formatter owns layout, and
|
|
6
|
+
the linter is told to stop having opinions about it**. sqlalign generates that
|
|
7
|
+
instruction rather than making a team hand-maintain it.
|
|
8
|
+
|
|
9
|
+
Two principles decide what goes in:
|
|
10
|
+
|
|
11
|
+
1. **Disable the whole `layout` GROUP, not a list of rules.** Naming individual
|
|
12
|
+
rules dates instantly: a sqlfluff upgrade that adds a layout rule would start
|
|
13
|
+
failing formatted output, and the config would need editing to catch up. The
|
|
14
|
+
group covers rules that do not exist yet.
|
|
15
|
+
|
|
16
|
+
2. **Keep every semantic rule ON.** `ambiguous.column_references`,
|
|
17
|
+
`aliasing.expression`, `convention.casting_style`,
|
|
18
|
+
`structure.join_condition_order` and the rest lint the AUTHOR'S SQL, which is
|
|
19
|
+
exactly what a linter is for. sqlalign preserves those choices rather than
|
|
20
|
+
rewriting them, so there is no conflict to resolve, and silencing them would
|
|
21
|
+
quietly narrow what the team's linter is allowed to notice.
|
|
22
|
+
|
|
23
|
+
(The repository's own `.sqlfluff` DOES exclude three of them. That is a
|
|
24
|
+
different file with a different job: it gates a fixture set that deliberately
|
|
25
|
+
mixes styles. It is not what a user should run.)
|
|
26
|
+
|
|
27
|
+
Everything else here is a genuine collision, where sqlalign and sqlfluff both
|
|
28
|
+
have a defensible opinion and must be told to agree. Each is derived from the
|
|
29
|
+
user's effective `Style`, so a team that sets `keyword_case = "lower"` gets a
|
|
30
|
+
config that expects lowercase rather than one that immediately contradicts them.
|
|
31
|
+
"""
|
|
32
|
+
from sqlalign.style import Style
|
|
33
|
+
|
|
34
|
+
# The sqlfluff release this mapping was checked against. Stamped into the output
|
|
35
|
+
# so a future reader can tell whether the config predates their linter: rule
|
|
36
|
+
# names and config keys are versioned surface, and a silent mismatch reads as
|
|
37
|
+
# "sqlalign generated a broken config" rather than "these have drifted apart".
|
|
38
|
+
TESTED_SQLFLUFF = "4.2.2"
|
|
39
|
+
|
|
40
|
+
# style knob -> (sqlfluff rule, config key, {style value: sqlfluff value})
|
|
41
|
+
_MAPPINGS = (
|
|
42
|
+
# sqlalign prints `AS` on a table alias or omits it; sqlfluff's AL01 wants to
|
|
43
|
+
# know which, and defaults to `explicit`, so the house default (bare) fails
|
|
44
|
+
# a stock sqlfluff install on every joined query.
|
|
45
|
+
("table_alias_style", "aliasing.table", "aliasing",
|
|
46
|
+
{"bare": "implicit", "as": "explicit"}),
|
|
47
|
+
# Both spellings collapse at parse time, so sqlalign must pick one; CV01
|
|
48
|
+
# defaults to `consistent`, which is satisfied either way, but stating it
|
|
49
|
+
# means a hand-written statement that disagrees is reported.
|
|
50
|
+
("neq_style", "convention.not_equal", "preferred_not_equal_style",
|
|
51
|
+
{"!=": "c_style", "<>": "ansi"}),
|
|
52
|
+
("keyword_case", "capitalisation.keywords", "capitalisation_policy",
|
|
53
|
+
{"upper": "upper", "lower": "lower"}),
|
|
54
|
+
("keyword_case", "capitalisation.functions", "extended_capitalisation_policy",
|
|
55
|
+
{"upper": "upper", "lower": "lower"}),
|
|
56
|
+
("keyword_case", "capitalisation.literals", "capitalisation_policy",
|
|
57
|
+
{"upper": "upper", "lower": "lower"}),
|
|
58
|
+
("keyword_case", "capitalisation.types", "extended_capitalisation_policy",
|
|
59
|
+
{"upper": "upper", "lower": "lower"}),
|
|
60
|
+
)
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
def sqlfluff_config(style: Style, dialect: str) -> str:
|
|
64
|
+
"""The `.sqlfluff` a team should use next to this `style`."""
|
|
65
|
+
lines = [
|
|
66
|
+
f"# Generated by sqlalign for sqlfluff {TESTED_SQLFLUFF}. Regenerate with:",
|
|
67
|
+
"# sqlalign --print-sqlfluff-config > .sqlfluff",
|
|
68
|
+
"#",
|
|
69
|
+
"# sqlalign owns layout, so the whole `layout` rule GROUP is excluded --",
|
|
70
|
+
"# by group rather than by name, so a sqlfluff upgrade that adds a layout",
|
|
71
|
+
"# rule cannot start failing formatted output.",
|
|
72
|
+
"#",
|
|
73
|
+
"# Every semantic rule stays ON. Those lint your SQL, not sqlalign's",
|
|
74
|
+
"# whitespace, and sqlalign preserves the choices they are about.",
|
|
75
|
+
"[sqlfluff]",
|
|
76
|
+
f"dialect = {dialect}",
|
|
77
|
+
"exclude_rules = layout",
|
|
78
|
+
# Line length lives in the layout group and is therefore already off;
|
|
79
|
+
# stating it keeps the file honest if someone narrows exclude_rules.
|
|
80
|
+
"max_line_length = -1",
|
|
81
|
+
]
|
|
82
|
+
for knob, rule, key, table in _MAPPINGS:
|
|
83
|
+
value = table.get(getattr(style, knob))
|
|
84
|
+
if value is None: # a knob value with no sqlfluff analogue
|
|
85
|
+
continue
|
|
86
|
+
lines += ["", f"# from sqlalign's {knob}", f"[sqlfluff:rules:{rule}]",
|
|
87
|
+
f"{key} = {value}"]
|
|
88
|
+
return "\n".join(lines) + "\n"
|
sqlalign/style.py
ADDED
|
@@ -0,0 +1,215 @@
|
|
|
1
|
+
"""Style options. Layout handlers read these rather than hard-coding literals."""
|
|
2
|
+
from dataclasses import dataclass, field
|
|
3
|
+
|
|
4
|
+
from sqlalign.config import Width
|
|
5
|
+
|
|
6
|
+
# User-facing alignment targets, mapped to the internal segment kinds that
|
|
7
|
+
# implement them. Names are config-file surface: adding one is safe, renaming
|
|
8
|
+
# one is a breaking change.
|
|
9
|
+
ALIGN_TARGETS: dict[str, frozenset[str]] = {
|
|
10
|
+
"aliases": frozenset({"as", "alias"}), # both of the next two
|
|
11
|
+
"column_aliases": frozenset({"as"}), # `x AS foo`
|
|
12
|
+
"table_aliases": frozenset({"alias"}), # `FROM orders o`
|
|
13
|
+
"table_names": frozenset({"table"}), # the table after FROM/JOIN
|
|
14
|
+
"operators": frozenset({"op"}), # =, !=, <, LIKE, IS ...
|
|
15
|
+
"join_conditions": frozenset({"on"}), # the ON/AND column
|
|
16
|
+
"case_results": frozenset({"then"}), # THEN in a short-form CASE
|
|
17
|
+
"column_types": frozenset({"type"}), # CREATE TABLE types
|
|
18
|
+
"column_constraints": frozenset({"constraint", "nul", "enc"}),
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
ALL_ALIGN_TARGETS = frozenset(ALIGN_TARGETS)
|
|
22
|
+
|
|
23
|
+
# `align` alone enables every target except `table_names`, which pads the
|
|
24
|
+
# FROM/JOIN keyword so table names share a column: a different published style
|
|
25
|
+
# rather than a refinement of this one. It remains a legal setting.
|
|
26
|
+
HOUSE_ALIGN_TARGETS = ALL_ALIGN_TARGETS - {"table_names"}
|
|
27
|
+
|
|
28
|
+
# Dialects whose emitted keywords are verified valid.
|
|
29
|
+
#
|
|
30
|
+
# The AST check cannot catch dialect-invalid output. sqlglot parses more
|
|
31
|
+
# leniently than any single engine: T-SQL `SELECT TOP 10 id` yields the same
|
|
32
|
+
# `Limit` node Postgres uses, the layout emits `LIMIT`, and sqlglot reads that
|
|
33
|
+
# back as T-SQL too, so the comparison passes and SQL Server rejects the
|
|
34
|
+
# result. Adding a dialect means auditing every keyword the handlers emit.
|
|
35
|
+
SUPPORTED_DIALECTS = frozenset({"postgres", "redshift", "tsql"})
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
@dataclass(frozen=True)
|
|
39
|
+
class Style:
|
|
40
|
+
width: Width = field(default_factory=Width)
|
|
41
|
+
|
|
42
|
+
# Master switch. Off emits every segment one space apart, keeping the
|
|
43
|
+
# same line structure without the padding.
|
|
44
|
+
align: bool = True
|
|
45
|
+
|
|
46
|
+
# Which targets participate when `align` is on. An omitted target is
|
|
47
|
+
# emitted untagged, so its column collapses to single spaces.
|
|
48
|
+
align_targets: frozenset[str] = field(default_factory=lambda: HOUSE_ALIGN_TARGETS)
|
|
49
|
+
|
|
50
|
+
# Whether to format inside dollar-quoted ($$) plpgsql bodies. Off passes
|
|
51
|
+
# the whole CREATE FUNCTION/PROCEDURE through byte-identical.
|
|
52
|
+
format_dollar_bodies: bool = True
|
|
53
|
+
|
|
54
|
+
# Output spelling for the two distinctions sqlglot collapses at parse time,
|
|
55
|
+
# so one has to be chosen when printing. Everything it preserves: cast
|
|
56
|
+
# form, GROUP BY references, alias presence, identifier case: is passed
|
|
57
|
+
# through untouched and is not a knob.
|
|
58
|
+
neq_style: str = "!=" # "!=" | "<>"
|
|
59
|
+
decimal_style: str = "NUMERIC" # "NUMERIC" | "DECIMAL"
|
|
60
|
+
|
|
61
|
+
# `FROM orders o` or `FROM orders AS o`. A third collapsed spelling: both
|
|
62
|
+
# forms parse identically, so the printed one is chosen here.
|
|
63
|
+
table_alias_style: str = "bare" # "bare" | "as"
|
|
64
|
+
|
|
65
|
+
# Where the separator sits in a stacked list.
|
|
66
|
+
comma_position: str = "leading" # "leading" | "trailing"
|
|
67
|
+
|
|
68
|
+
# Where AND/OR sit when a predicate spans lines.
|
|
69
|
+
boolean_operator_position: str = "leading" # "leading" | "trailing"
|
|
70
|
+
|
|
71
|
+
# Whether a JOIN's ON rides the table-reference line or drops below it.
|
|
72
|
+
# `own_line` retires the FROM-block-global ON column, so `join_conditions`
|
|
73
|
+
# has nothing to act on.
|
|
74
|
+
on_placement: str = "inline" # "inline" | "own_line"
|
|
75
|
+
|
|
76
|
+
# Whether the first select item rides the SELECT line.
|
|
77
|
+
select_placement: str = "inline" # "inline" | "own_line"
|
|
78
|
+
|
|
79
|
+
# `river` right-aligns root keywords so their last character lands on the
|
|
80
|
+
# gutter, putting every clause body in one column. A keyword wider than the
|
|
81
|
+
# gutter hangs on the far side.
|
|
82
|
+
clause_keyword_align: str = "left" # "left" | "river"
|
|
83
|
+
|
|
84
|
+
# The column a river's keywords right-align to. 6 is the width of SELECT.
|
|
85
|
+
river_gutter: int = 6
|
|
86
|
+
|
|
87
|
+
# List indent under `select_placement="own_line"`. Ignored when inline,
|
|
88
|
+
# where the column is len("SELECT ").
|
|
89
|
+
select_indent: int = 2
|
|
90
|
+
|
|
91
|
+
# Blank lines between the elements of a plpgsql body (DECLARE, BEGIN, each
|
|
92
|
+
# statement, END). Separate from `blank_lines_between_statements`.
|
|
93
|
+
body_blank_lines: int = 1
|
|
94
|
+
|
|
95
|
+
# Mask Jinja/dbt expressions ({{ }}, {% %}, {# #}) so a templated model
|
|
96
|
+
# parses. Placeholders keep the original width, so alignment columns are
|
|
97
|
+
# computed against the real text. Harmless when absent.
|
|
98
|
+
protect_templating: bool = True
|
|
99
|
+
|
|
100
|
+
# Case for keywords, function names and type names. Identifiers and string
|
|
101
|
+
# literals are never touched.
|
|
102
|
+
keyword_case: str = "upper" # "upper" | "lower"
|
|
103
|
+
|
|
104
|
+
# `None` applies the house rule: one blank line between two multi-line
|
|
105
|
+
# statements, none otherwise. An integer forces that many between every pair.
|
|
106
|
+
blank_lines_between_statements: int | None = None
|
|
107
|
+
|
|
108
|
+
def __post_init__(self):
|
|
109
|
+
if self.keyword_case not in ("upper", "lower"):
|
|
110
|
+
raise ValueError(
|
|
111
|
+
f"keyword_case must be 'upper' or 'lower', got {self.keyword_case!r}")
|
|
112
|
+
blanks = self.blank_lines_between_statements
|
|
113
|
+
if blanks is not None and (not isinstance(blanks, int) or isinstance(blanks, bool)
|
|
114
|
+
or blanks < 0):
|
|
115
|
+
raise ValueError("blank_lines_between_statements must be a non-negative "
|
|
116
|
+
f"integer or unset, got {blanks!r}")
|
|
117
|
+
unknown = sorted(set(self.align_targets) - ALL_ALIGN_TARGETS)
|
|
118
|
+
if unknown:
|
|
119
|
+
raise ValueError(
|
|
120
|
+
f"unknown align_targets {unknown}; valid: {sorted(ALL_ALIGN_TARGETS)}")
|
|
121
|
+
if self.comma_position not in ("leading", "trailing"):
|
|
122
|
+
raise ValueError(
|
|
123
|
+
f"comma_position must be 'leading' or 'trailing', got {self.comma_position!r}")
|
|
124
|
+
if self.boolean_operator_position not in ("leading", "trailing"):
|
|
125
|
+
raise ValueError("boolean_operator_position must be 'leading' or 'trailing', "
|
|
126
|
+
f"got {self.boolean_operator_position!r}")
|
|
127
|
+
if self.on_placement not in ("inline", "own_line"):
|
|
128
|
+
raise ValueError(
|
|
129
|
+
f"on_placement must be 'inline' or 'own_line', got {self.on_placement!r}")
|
|
130
|
+
if (not isinstance(self.body_blank_lines, int)
|
|
131
|
+
or isinstance(self.body_blank_lines, bool) or self.body_blank_lines < 0):
|
|
132
|
+
raise ValueError("body_blank_lines must be a non-negative integer, got "
|
|
133
|
+
f"{self.body_blank_lines!r}")
|
|
134
|
+
if self.clause_keyword_align not in ("left", "river"):
|
|
135
|
+
raise ValueError("clause_keyword_align must be 'left' or 'river', got "
|
|
136
|
+
f"{self.clause_keyword_align!r}")
|
|
137
|
+
if (not isinstance(self.river_gutter, int) or isinstance(self.river_gutter, bool)
|
|
138
|
+
or self.river_gutter < 2):
|
|
139
|
+
raise ValueError(f"river_gutter must be an integer >= 2, got {self.river_gutter!r}")
|
|
140
|
+
if self.select_placement not in ("inline", "own_line"):
|
|
141
|
+
raise ValueError("select_placement must be 'inline' or 'own_line', got "
|
|
142
|
+
f"{self.select_placement!r}")
|
|
143
|
+
if (not isinstance(self.select_indent, int) or isinstance(self.select_indent, bool)
|
|
144
|
+
or self.select_indent < 1):
|
|
145
|
+
raise ValueError("select_indent must be a positive integer, got "
|
|
146
|
+
f"{self.select_indent!r}")
|
|
147
|
+
if self.neq_style not in ("!=", "<>"):
|
|
148
|
+
raise ValueError(f"neq_style must be '!=' or '<>', got {self.neq_style!r}")
|
|
149
|
+
if self.decimal_style not in ("NUMERIC", "DECIMAL"):
|
|
150
|
+
raise ValueError(
|
|
151
|
+
f"decimal_style must be 'NUMERIC' or 'DECIMAL', got {self.decimal_style!r}")
|
|
152
|
+
if self.table_alias_style not in ("bare", "as"):
|
|
153
|
+
raise ValueError("table_alias_style must be 'bare' or 'as', got "
|
|
154
|
+
f"{self.table_alias_style!r}")
|
|
155
|
+
|
|
156
|
+
|
|
157
|
+
HOUSE = Style()
|
|
158
|
+
COMPACT = Style(align=False)
|
|
159
|
+
|
|
160
|
+
# Named starting points, so a team picks one word instead of reading nine knobs.
|
|
161
|
+
# A preset only sets a BASE: config-file keys and command-line flags still layer
|
|
162
|
+
# on top of it, so `preset = "compact"` plus `comma_position = "trailing"` is a
|
|
163
|
+
# legitimate combination rather than an either/or.
|
|
164
|
+
#
|
|
165
|
+
# The `dbt` preset was deliberately withheld until `keyword_case` existed, on the
|
|
166
|
+
# grounds that a preset getting the commas right and the casing wrong would look
|
|
167
|
+
# official while being wrong. With casing, comma position and padding all now
|
|
168
|
+
# expressible it is substantially accurate, and it ships with its one remaining
|
|
169
|
+
# deviation stated: dbt indents nested blocks 4, sqlalign indents a CTE body 2
|
|
170
|
+
# (see the dropped `indent_unit`: sqlalign's indent literals are three
|
|
171
|
+
# different concepts, not one knob).
|
|
172
|
+
PRESETS: dict[str, dict] = {
|
|
173
|
+
# The columnar house style: aligned, leading separators, ON inline.
|
|
174
|
+
"house": {},
|
|
175
|
+
# Same line structure, no alignment padding. 9 of 10 published SQL style
|
|
176
|
+
# guides produce unpadded output, so this is the widest-reach starting point.
|
|
177
|
+
"compact": {"align": False},
|
|
178
|
+
# Keeps the alignment but moves both separators to the end of the line, for
|
|
179
|
+
# teams that align yet write trailing commas (8 of 10 guides) and trailing
|
|
180
|
+
# booleans (7 of 10).
|
|
181
|
+
"trailing": {"comma_position": "trailing",
|
|
182
|
+
"boolean_operator_position": "trailing"},
|
|
183
|
+
# dbt / analytics-engineering conventions: lowercase everything, the select
|
|
184
|
+
# list stacked under a bare `select` at 4: dbt's own guide, and the reason
|
|
185
|
+
# this preset states the indent rather than taking the default 2: trailing
|
|
186
|
+
# commas, no columnar padding. Deviation: a CTE body indents 2, not 4.
|
|
187
|
+
"dbt": {"keyword_case": "lower", "comma_position": "trailing", "align": False,
|
|
188
|
+
"select_placement": "own_line", "select_indent": 4},
|
|
189
|
+
# Holywell's river (sqlstyle.guide) and its two verbatim forks. Table-alias
|
|
190
|
+
# padding is off: that column would span rows at two different indents (FROM
|
|
191
|
+
# sits in the gutter, JOINs on the far side of it) and stretch absurdly.
|
|
192
|
+
# River is a structural style, not a columnar one.
|
|
193
|
+
"river": {"clause_keyword_align": "river", "on_placement": "own_line",
|
|
194
|
+
"align": False},
|
|
195
|
+
# GitLab's published SQL style guide (handbook.gitlab.com, "SQL Style Guide"),
|
|
196
|
+
# taken from the linter-processed "Example Code" section rather than the prose
|
|
197
|
+
# examples where the two disagree: their .sqlfluff config and that section
|
|
198
|
+
# both use a 2-space step, the prose uses 4.
|
|
199
|
+
#
|
|
200
|
+
# Their config asks for exactly one alignment ("aligning column aliases within
|
|
201
|
+
# the SELECT statement"), which is why `align_targets` is that one target
|
|
202
|
+
# rather than `align = false`: the rest of the line structure is still
|
|
203
|
+
# sqlalign's, only the padding is theirs.
|
|
204
|
+
"gitlab": {"comma_position": "trailing", "on_placement": "own_line",
|
|
205
|
+
"select_placement": "own_line",
|
|
206
|
+
"table_alias_style": "as",
|
|
207
|
+
"align_targets": frozenset({"column_aliases"})},
|
|
208
|
+
}
|
|
209
|
+
|
|
210
|
+
|
|
211
|
+
def preset_style(name: str, **overrides) -> Style:
|
|
212
|
+
"""A Style from a named preset, with any keyword overrides applied on top."""
|
|
213
|
+
if name not in PRESETS:
|
|
214
|
+
raise ValueError(f"unknown preset {name!r}; valid: {sorted(PRESETS)}")
|
|
215
|
+
return Style(**{**PRESETS[name], **overrides})
|
sqlalign/templating.py
ADDED
|
@@ -0,0 +1,87 @@
|
|
|
1
|
+
"""Template-expression protection (Jinja / dbt).
|
|
2
|
+
|
|
3
|
+
A dbt model is not valid SQL — `select * from {{ ref('orders') }}` does not parse,
|
|
4
|
+
so sqlalign could not format one at all: it declined and passed the file through.
|
|
5
|
+
This module masks each template expression with a placeholder, lets the normal
|
|
6
|
+
engine format the result, then puts the original text back.
|
|
7
|
+
|
|
8
|
+
**Placeholders are LENGTH-PRESERVING, and that is the whole design.** sqlalign
|
|
9
|
+
computes alignment columns from rendered text widths, so a placeholder shorter or
|
|
10
|
+
longer than what it stands for would produce columns that are wrong the moment the
|
|
11
|
+
original is restored: every alias in a `FROM` block shifted by the difference
|
|
12
|
+
between `{{ ref('orders') }}` and whatever replaced it. Masking to the exact same
|
|
13
|
+
character count means every column is computed against the real width and survives
|
|
14
|
+
restoration untouched.
|
|
15
|
+
|
|
16
|
+
A template expression too short to hold a unique placeholder (fewer than
|
|
17
|
+
`_MIN_WIDTH` characters, e.g. `{{x}}`) is declined rather than approximated: the
|
|
18
|
+
statement passes through byte-identical, which is the house rule for anything the
|
|
19
|
+
engine cannot reproduce exactly.
|
|
20
|
+
|
|
21
|
+
The safety net compares the MASKED input against the MASKED output, not the raw
|
|
22
|
+
text: raw templated SQL does not parse, so there would be nothing to compare.
|
|
23
|
+
Since the mask is a pure bijection over the same character positions, equality of
|
|
24
|
+
the masked forms is equality of the originals.
|
|
25
|
+
"""
|
|
26
|
+
import re
|
|
27
|
+
|
|
28
|
+
# Jinja statement/expression/comment forms, in the order they must be tried.
|
|
29
|
+
DEFAULT_PATTERNS = (
|
|
30
|
+
r"\{\{.*?\}\}", # {{ ref('orders') }}
|
|
31
|
+
r"\{%.*?%\}", # {% if ... %}
|
|
32
|
+
r"\{#.*?#\}", # {# comment #}
|
|
33
|
+
)
|
|
34
|
+
|
|
35
|
+
_PREFIX = "_sqla_tpl_"
|
|
36
|
+
_MIN_WIDTH = len(_PREFIX) + 2 # prefix + at least one index digit + one pad
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
def _mask_for(index: int, width: int) -> str | None:
|
|
40
|
+
"""A placeholder of exactly `width` characters that lexes as one identifier.
|
|
41
|
+
|
|
42
|
+
The `_` closing the stem is load-bearing: it keeps no placeholder a prefix of
|
|
43
|
+
another (`_sqla_tpl_1_…` vs `_sqla_tpl_11_…`), and `unmask` substitutes them
|
|
44
|
+
one at a time by plain text replace, which a prefix would corrupt.
|
|
45
|
+
"""
|
|
46
|
+
stem = f"{_PREFIX}{index}_"
|
|
47
|
+
if width < len(stem):
|
|
48
|
+
return None
|
|
49
|
+
return stem + "x" * (width - len(stem))
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
def mask(text: str, patterns=DEFAULT_PATTERNS) -> tuple[str, dict[str, str]]:
|
|
53
|
+
"""Replace every template expression with a same-width placeholder.
|
|
54
|
+
|
|
55
|
+
Returns `(masked_text, {placeholder: original})`. Raises `ValueError` if any
|
|
56
|
+
expression is too short to mask, or if a generated placeholder would collide
|
|
57
|
+
with text already present: either way the caller passes the file through
|
|
58
|
+
rather than risking a wrong reconstruction.
|
|
59
|
+
"""
|
|
60
|
+
combined = re.compile("|".join(f"(?:{p})" for p in patterns), re.DOTALL)
|
|
61
|
+
replacements: dict[str, str] = {}
|
|
62
|
+
counter = 0
|
|
63
|
+
|
|
64
|
+
def _replace(match: re.Match) -> str:
|
|
65
|
+
nonlocal counter
|
|
66
|
+
original = match.group(0)
|
|
67
|
+
if len(original) < _MIN_WIDTH:
|
|
68
|
+
raise ValueError(f"template expression too short to mask: {original!r}")
|
|
69
|
+
placeholder = _mask_for(counter, len(original))
|
|
70
|
+
counter += 1
|
|
71
|
+
if placeholder is None or placeholder in text:
|
|
72
|
+
raise ValueError(f"cannot mask template expression: {original!r}")
|
|
73
|
+
replacements[placeholder] = original
|
|
74
|
+
return placeholder
|
|
75
|
+
|
|
76
|
+
return combined.sub(_replace, text), replacements
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
def unmask(text: str, replacements: dict[str, str]) -> str:
|
|
80
|
+
"""Put the original template expressions back."""
|
|
81
|
+
for placeholder, original in replacements.items():
|
|
82
|
+
text = text.replace(placeholder, original)
|
|
83
|
+
return text
|
|
84
|
+
|
|
85
|
+
|
|
86
|
+
def has_templating(text: str, patterns=DEFAULT_PATTERNS) -> bool:
|
|
87
|
+
return any(re.search(p, text, re.DOTALL) for p in patterns)
|