mirqab 0.4.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.
mirqab/__init__.py ADDED
@@ -0,0 +1,33 @@
1
+ __version__ = "0.4.0"
2
+
3
+ from mirqab.api import ( # noqa: E402
4
+ ReadOnlyError,
5
+ load_config,
6
+ post_to_slack,
7
+ render_markdown,
8
+ render_slack,
9
+ review_to_dict,
10
+ run_review,
11
+ )
12
+ from mirqab.config import Config, ConfigError # noqa: E402
13
+ from mirqab.models import Review # noqa: E402
14
+ from mirqab.report_slack import SlackReport # noqa: E402
15
+ from mirqab.slack import SlackError # noqa: E402
16
+ from mirqab.sources.base import SourceError # noqa: E402
17
+
18
+ __all__ = [
19
+ "Config",
20
+ "ConfigError",
21
+ "ReadOnlyError",
22
+ "Review",
23
+ "SlackError",
24
+ "SlackReport",
25
+ "SourceError",
26
+ "__version__",
27
+ "load_config",
28
+ "post_to_slack",
29
+ "render_markdown",
30
+ "render_slack",
31
+ "review_to_dict",
32
+ "run_review",
33
+ ]
File without changes
@@ -0,0 +1,131 @@
1
+ from collections import defaultdict
2
+ from datetime import datetime, timedelta
3
+
4
+ from mirqab.config import ReviewSettings
5
+ from mirqab.models import (
6
+ DuplicateIndex,
7
+ ForeignKeyInfo,
8
+ Hygiene,
9
+ IndexInfo,
10
+ MissingFkIndex,
11
+ TableInfo,
12
+ UnusedIndex,
13
+ VacuumStatus,
14
+ )
15
+
16
+ UNUSED_CAUTION = ("A low scan count means rarely read, not never read: search the application code for "
17
+ "queries on this column before dropping. Usage on a read replica is not counted here.")
18
+
19
+
20
+ def covers(index: IndexInfo, columns: list[str]) -> bool:
21
+ n = len(columns)
22
+ if not n or index.predicate or not index.is_valid or len(index.columns) < n:
23
+ return False
24
+ return set(index.columns[:n]) == set(columns) and "(expression)" not in index.columns[:n]
25
+
26
+
27
+ def mark_fk_covering(indexes: list[IndexInfo], fks: list[ForeignKeyInfo]) -> None:
28
+ by_table: dict[int, list[ForeignKeyInfo]] = defaultdict(list)
29
+ for fk in fks:
30
+ by_table[fk.table_id].append(fk)
31
+ for index in indexes:
32
+ index.covers_fk = any(covers(index, fk.columns) for fk in by_table.get(index.table_id, []))
33
+
34
+
35
+ def unused_indexes(indexes: list[IndexInfo], tables: dict[int, TableInfo], settings: ReviewSettings,
36
+ now: datetime, has_last_idx_scan: bool) -> list[UnusedIndex]:
37
+ min_bytes = settings.unused_index_min_mb * 1024 * 1024
38
+ cutoff = now - timedelta(days=settings.unused_index_days)
39
+ out = []
40
+ for ix in indexes:
41
+ if ix.is_unique or ix.is_primary or ix.backs_constraint or ix.covers_fk or not ix.is_valid:
42
+ continue
43
+ if ix.bytes < min_bytes:
44
+ continue
45
+ stale = ix.idx_scan == 0 or (has_last_idx_scan and ix.last_idx_scan is not None
46
+ and ix.last_idx_scan < cutoff)
47
+ if not stale:
48
+ continue
49
+ table = tables.get(ix.table_id)
50
+ out.append(UnusedIndex(ix, table.writes if table else 0))
51
+ out.sort(key=lambda u: u.index.bytes, reverse=True)
52
+ return out
53
+
54
+
55
+ def duplicate_indexes(indexes: list[IndexInfo]) -> list[DuplicateIndex]:
56
+ by_table: dict[int, list[IndexInfo]] = defaultdict(list)
57
+ for ix in indexes:
58
+ if ix.is_valid and not ix.has_expressions:
59
+ by_table[ix.table_id].append(ix)
60
+ out: list[DuplicateIndex] = []
61
+ seen: set[int] = set()
62
+ for group in by_table.values():
63
+ group.sort(key=lambda i: (len(i.columns), i.name))
64
+ for a in group:
65
+ if a.is_unique or a.is_primary or a.backs_constraint or a.index_id in seen \
66
+ or " INCLUDE (" in a.definition:
67
+ continue
68
+ for b in group:
69
+ if b is a or b.index_id in seen:
70
+ continue
71
+ if a.method != b.method or (a.predicate or "") != (b.predicate or ""):
72
+ continue
73
+ n = len(a.columns)
74
+ if n == 0 or len(b.columns) < n or b.columns[:n] != a.columns:
75
+ continue
76
+ if a.opclasses[:n] != b.opclasses[:n]:
77
+ continue
78
+ if len(b.columns) == n and (b.index_id > a.index_id) and not (b.is_unique or b.backs_constraint):
79
+ continue
80
+ out.append(DuplicateIndex(redundant=a, covered_by=b))
81
+ seen.add(a.index_id)
82
+ break
83
+ out.sort(key=lambda d: d.redundant.bytes, reverse=True)
84
+ return out
85
+
86
+
87
+ def invalid_indexes(indexes: list[IndexInfo]) -> list[IndexInfo]:
88
+ return [ix for ix in indexes if not ix.is_valid]
89
+
90
+
91
+ def fks_without_index(fks: list[ForeignKeyInfo], indexes: list[IndexInfo], tables: dict[int, TableInfo],
92
+ settings: ReviewSettings) -> list[MissingFkIndex]:
93
+ by_table: dict[int, list[IndexInfo]] = defaultdict(list)
94
+ for ix in indexes:
95
+ by_table[ix.table_id].append(ix)
96
+ out = []
97
+ for fk in fks:
98
+ table = tables.get(fk.table_id)
99
+ if table is None or table.reltuples < settings.big_table_rows:
100
+ continue
101
+ if not any(covers(ix, fk.columns) for ix in by_table.get(fk.table_id, [])):
102
+ out.append(MissingFkIndex(fk, table.reltuples))
103
+ out.sort(key=lambda m: m.reltuples, reverse=True)
104
+ return out
105
+
106
+
107
+ def vacuum_status(tables: list[TableInfo], settings: ReviewSettings) -> list[VacuumStatus]:
108
+ out = []
109
+ for t in tables:
110
+ reasons = []
111
+ if t.n_dead_tup >= 100_000 and t.n_dead_tup >= 0.2 * max(t.n_live_tup, 1):
112
+ reasons.append(f"{t.n_dead_tup:,} dead rows ({t.dead_ratio:.0%} of live rows)")
113
+ visible = t.all_visible_ratio
114
+ if visible is not None and visible < 0.5 and t.reltuples >= settings.big_table_rows:
115
+ reasons.append(f"only {visible:.0%} of pages are all-visible (index-only scans must visit the table)")
116
+ out.append(VacuumStatus(t, bool(reasons), "; ".join(reasons)))
117
+ return out
118
+
119
+
120
+ def build_hygiene(indexes: list[IndexInfo], tables: list[TableInfo], fks: list[ForeignKeyInfo],
121
+ settings: ReviewSettings, now: datetime, has_last_idx_scan: bool,
122
+ referenced_tables: list[TableInfo]) -> Hygiene:
123
+ mark_fk_covering(indexes, fks)
124
+ by_id = {t.relid: t for t in tables}
125
+ return Hygiene(
126
+ unused=unused_indexes(indexes, by_id, settings, now, has_last_idx_scan),
127
+ duplicates=duplicate_indexes(indexes),
128
+ invalid=invalid_indexes(indexes),
129
+ fk_missing=fks_without_index(fks, indexes, by_id, settings),
130
+ vacuum=vacuum_status(referenced_tables, settings),
131
+ )
@@ -0,0 +1,320 @@
1
+ """Replace $n placeholders with values a plain EXPLAIN can plan.
2
+
3
+ Used when the source cannot send $n (Metabase binds them as real JDBC parameters) or the server
4
+ has no EXPLAIN (GENERIC_PLAN) (PostgreSQL < 16).
5
+ """
6
+
7
+ import re
8
+ from dataclasses import dataclass, field
9
+
10
+ import sqlglot
11
+ from sqlglot import exp
12
+
13
+ from mirqab.analyze.sqltext import bare_name
14
+ from mirqab.sqllex import mask_sql
15
+
16
+ ColumnTypes = dict[tuple[str, str], str]
17
+
18
+ _PARAM = re.compile(r"(?<![\w$])\$(\d+)(?!\w)")
19
+ _TYPED_LITERAL = re.compile(r"\b(timestamptz|timestamp|date|time|interval)\s+\$(\d+)(?!\w)", re.IGNORECASE)
20
+ _COMPARISONS = (exp.EQ, exp.NEQ, exp.GT, exp.GTE, exp.LT, exp.LTE, exp.Like, exp.ILike)
21
+ _BOOLEAN_PARENTS = (exp.Where, exp.And, exp.Or, exp.Not, exp.Having)
22
+ MAX_LIMIT = 1000
23
+ DEFAULT_LIMIT = 50
24
+
25
+
26
+ @dataclass
27
+ class Substitution:
28
+ sql: str
29
+ replacements: dict[int, str] = field(default_factory=dict)
30
+ untyped: list[int] = field(default_factory=list)
31
+
32
+
33
+ def _identifier(ident) -> str:
34
+ if isinstance(ident, exp.Identifier):
35
+ return ident.this if ident.quoted else ident.this.lower()
36
+ return str(ident or "")
37
+
38
+
39
+ def _table_name(table: exp.Table) -> str:
40
+ return _identifier(table.args.get("this"))
41
+
42
+
43
+ def _alias(table: exp.Table) -> str:
44
+ alias = table.args.get("alias")
45
+ return _identifier(alias.this) if alias is not None else ""
46
+
47
+
48
+ def _sources(node: exp.Expression) -> list[exp.Table]:
49
+ """Tables named directly in this scope's FROM / JOIN / USING / target, not in nested subqueries."""
50
+ found: list[exp.Table] = []
51
+ for key in ("this", "from_", "from", "joins", "using", "tables"):
52
+ value = node.args.get(key)
53
+ for item in value if isinstance(value, list) else [value]:
54
+ if item is None:
55
+ continue
56
+ if isinstance(item, exp.Schema):
57
+ item = item.this
58
+ if isinstance(item, (exp.From, exp.Join)):
59
+ item = item.this
60
+ if isinstance(item, exp.Table):
61
+ found.append(item)
62
+ return found
63
+
64
+
65
+ def _scopes(node: exp.Expression):
66
+ current = node.parent
67
+ while current is not None:
68
+ if isinstance(current, (exp.Select, exp.Update, exp.Delete, exp.Insert)):
69
+ yield current
70
+ current = current.parent
71
+
72
+
73
+ class _Resolver:
74
+ def __init__(self, tree: exp.Expression, types: ColumnTypes):
75
+ self.types = types
76
+ self.by_table: dict[str, dict[str, str]] = {}
77
+ for (table, column), type_ in types.items():
78
+ self.by_table.setdefault(bare_name(table), {})[column] = type_
79
+ self.all_tables = list(tree.find_all(exp.Table))
80
+
81
+ def column_type(self, column: exp.Column) -> str | None:
82
+ ref = self.column_ref(column)
83
+ return ref[1] if ref else None
84
+
85
+ def column_ref(self, column: exp.Column) -> tuple[str, str] | None:
86
+ name = _identifier(column.this)
87
+ qualifier = _identifier(column.args.get("table")) if column.args.get("table") else ""
88
+ for scope in _scopes(column):
89
+ tables = _sources(scope)
90
+ if qualifier:
91
+ for t in tables:
92
+ if qualifier in (_alias(t), _table_name(t)):
93
+ return self._lookup(_table_name(t), name)
94
+ else:
95
+ hits = [(_table_name(t), self.by_table[_table_name(t)][name]) for t in tables
96
+ if name in self.by_table.get(_table_name(t), {})]
97
+ if len({type_ for _, type_ in hits}) == 1:
98
+ return hits[0]
99
+ if qualifier:
100
+ for t in self.all_tables:
101
+ if qualifier in (_alias(t), _table_name(t)):
102
+ return self._lookup(_table_name(t), name)
103
+ return None
104
+ hits = [(_table_name(t), self.by_table[_table_name(t)][name]) for t in self.all_tables
105
+ if name in self.by_table.get(_table_name(t), {})]
106
+ return hits[0] if len({type_ for _, type_ in hits}) == 1 else None
107
+
108
+ def _lookup(self, table: str, name: str) -> tuple[str, str] | None:
109
+ type_ = self.by_table.get(table, {}).get(name)
110
+ return (table, type_) if type_ else None
111
+
112
+
113
+ def _strip(node: exp.Expression) -> exp.Expression:
114
+ while isinstance(node, (exp.Paren, exp.Cast)):
115
+ node = node.this
116
+ return node
117
+
118
+
119
+ @dataclass
120
+ class ParamUse:
121
+ """How a $n is used. kind: equal, any, lower, upper (a range bound), fixed (value known) or typed."""
122
+ kind: str
123
+ type_: str | None = None
124
+ table: str = ""
125
+ column: str = ""
126
+ column_type: str | None = None
127
+ fixed: str | None = None
128
+ cast: bool = False
129
+
130
+ def placeholder(self) -> str | None:
131
+ if self.fixed is not None:
132
+ return self.fixed
133
+ if not self.type_:
134
+ return None
135
+ if self.kind == "any" and not self.cast:
136
+ array = self.type_ if self.type_.endswith("[]") else f"{self.type_}[]"
137
+ return f"{_null(array)}::{array}"
138
+ return _null(self.type_)
139
+
140
+
141
+ _RANGE = {exp.GT: "lower", exp.GTE: "lower", exp.LT: "upper", exp.LTE: "upper"}
142
+ _FLIPPED = {"lower": "upper", "upper": "lower"}
143
+
144
+
145
+ def _climb(node: exp.Expression) -> tuple[exp.Expression, exp.Expression | None]:
146
+ parent = node.parent
147
+ while isinstance(parent, exp.Paren) and not isinstance(parent.parent, exp.Any):
148
+ node, parent = parent, parent.parent
149
+ return node, parent
150
+
151
+
152
+ def _column_use(kind: str, column: exp.Expression, resolver: _Resolver, type_: str | None = None) -> ParamUse | None:
153
+ target = _strip(column)
154
+ if not isinstance(target, exp.Column):
155
+ return None
156
+ ref = resolver.column_ref(target)
157
+ table, column_type = ref if ref else ("", None)
158
+ if type_ is None:
159
+ type_ = column_type
160
+ return ParamUse(kind, type_, table, _identifier(target.this), column_type)
161
+
162
+
163
+ def _compared(node: exp.Expression, parent: exp.Expression | None, resolver: _Resolver) -> ParamUse | None:
164
+ if isinstance(parent, _COMPARISONS):
165
+ other = parent.expression if node.arg_key == "this" else parent.this
166
+ while isinstance(other, exp.Paren):
167
+ other = other.this
168
+ kind = _RANGE.get(type(parent), "equal")
169
+ if node.arg_key == "this" and kind in _FLIPPED:
170
+ kind = _FLIPPED[kind]
171
+ if isinstance(other, exp.Cast) and isinstance(_strip(other), exp.Column):
172
+ return _column_use(kind, other, resolver, other.to.sql(dialect="postgres"))
173
+ if isinstance(_strip(other), exp.Column):
174
+ return _column_use(kind, other, resolver)
175
+ return ParamUse("unknown")
176
+ if isinstance(parent, exp.Paren) and isinstance(parent.parent, exp.Any):
177
+ comparison = parent.parent.parent
178
+ if isinstance(comparison, _COMPARISONS):
179
+ column = comparison.this if parent.parent.arg_key == "expression" else comparison.expression
180
+ return _column_use("any", column, resolver) or ParamUse("unknown")
181
+ return ParamUse("unknown")
182
+ if isinstance(parent, exp.In) and node.arg_key == "expressions":
183
+ return _column_use("equal", parent.this, resolver) or ParamUse("unknown")
184
+ if isinstance(parent, exp.Between) and node.arg_key in ("low", "high"):
185
+ kind = "lower" if node.arg_key == "low" else "upper"
186
+ return _column_use(kind, parent.this, resolver) or ParamUse("unknown")
187
+ return None
188
+
189
+
190
+ def _infer_use(param: exp.Parameter, resolver: _Resolver, limit_value: int) -> ParamUse | None:
191
+ node, parent = _climb(param)
192
+ if isinstance(parent, exp.Cast):
193
+ type_ = parent.to.sql(dialect="postgres")
194
+ outer, outer_parent = _climb(parent)
195
+ use = _compared(outer, outer_parent, resolver)
196
+ if use is not None and use.kind != "unknown":
197
+ return ParamUse(use.kind, type_, use.table, use.column, use.column_type, cast=True)
198
+ return ParamUse("typed", type_, cast=True)
199
+ if isinstance(parent, exp.Limit):
200
+ return ParamUse("fixed", fixed=str(limit_value))
201
+ if isinstance(parent, exp.Offset):
202
+ return ParamUse("fixed", fixed="0")
203
+ if isinstance(parent, exp.Select) and node.arg_key == "expressions":
204
+ return ParamUse("fixed", fixed="1")
205
+ if isinstance(parent, exp.Alias) and isinstance(parent.parent, exp.Select):
206
+ return ParamUse("fixed", fixed="1")
207
+ use = _compared(node, parent, resolver)
208
+ if use is not None:
209
+ return use
210
+ if isinstance(parent, exp.Tuple) and isinstance(parent.parent, exp.Values):
211
+ insert = parent.parent.parent
212
+ if isinstance(insert, exp.Insert):
213
+ type_ = _insert_value(insert, parent, node, resolver)
214
+ return ParamUse("typed", type_) if type_ else None
215
+ if isinstance(parent, _BOOLEAN_PARENTS) or (isinstance(parent, exp.Join) and node.arg_key == "on"):
216
+ return ParamUse("fixed", fixed="true")
217
+ return None
218
+
219
+
220
+ def _insert_value(insert: exp.Insert, row: exp.Tuple, node: exp.Expression, resolver: _Resolver) -> str | None:
221
+ target = insert.this
222
+ columns: list[str] = []
223
+ table = target.this if isinstance(target, exp.Schema) else target
224
+ if isinstance(target, exp.Schema):
225
+ columns = [_identifier(c) for c in target.expressions]
226
+ if not isinstance(table, exp.Table):
227
+ return None
228
+ known = resolver.by_table.get(_table_name(table), {})
229
+ if not columns:
230
+ columns = list(known)
231
+ index = row.expressions.index(node) if node in row.expressions else -1
232
+ if 0 <= index < len(columns) and (type_ := known.get(columns[index])):
233
+ return type_
234
+ return None
235
+
236
+
237
+ def _null(type_: str) -> str:
238
+ return f"(SELECT NULL::{type_})"
239
+
240
+
241
+ def _spaced(sql: str) -> str:
242
+ masked = mask_sql(sql)
243
+ out, last = [], 0
244
+ for m in _PARAM.finditer(masked):
245
+ out += [sql[last:m.start()], f" ${m.group(1)} "]
246
+ last = m.end()
247
+ return "".join(out) + sql[last:]
248
+
249
+
250
+ def param_uses(sql: str, column_types: ColumnTypes, rows_per_call: float | None = None) -> dict[int, ParamUse | None]:
251
+ """How each $n in `sql` is used, for the placeholder values of a plan or for sample values."""
252
+ limit_value = DEFAULT_LIMIT if rows_per_call is None else min(MAX_LIMIT, max(1, round(rows_per_call)))
253
+ masked = mask_sql(sql)
254
+ numbers = sorted({int(m.group(1)) for m in _PARAM.finditer(masked)})
255
+ uses: dict[int, ParamUse | None] = {}
256
+ if not numbers:
257
+ return uses
258
+ for m in _TYPED_LITERAL.finditer(masked):
259
+ uses.setdefault(int(m.group(2)), ParamUse("typed", m.group(1).lower()))
260
+ try:
261
+ tree = sqlglot.parse_one(_spaced(_rewrite_typed_literals(sql, masked)), read="postgres")
262
+ except Exception:
263
+ tree = None
264
+ if tree is not None:
265
+ resolver = _Resolver(tree, column_types)
266
+ for param in tree.find_all(exp.Parameter):
267
+ if not param.name.isdigit():
268
+ continue
269
+ n = int(param.name)
270
+ current = uses.get(n)
271
+ if current is not None and current.placeholder() is not None:
272
+ continue
273
+ found = _infer_use(param, resolver, limit_value)
274
+ if current is None or (found is not None and found.placeholder() is not None):
275
+ uses[n] = found
276
+ return {n: uses.get(n) for n in numbers}
277
+
278
+
279
+ def substitute_params(sql: str, column_types: ColumnTypes, rows_per_call: float | None = None,
280
+ *, untyped_fallback: bool = True) -> Substitution:
281
+ uses = param_uses(sql, column_types, rows_per_call)
282
+ if not uses:
283
+ return Substitution(sql)
284
+ replacements: dict[int, str] = {}
285
+ for n, use in uses.items():
286
+ if use is not None and (value := use.placeholder()) is not None:
287
+ replacements[n] = value
288
+ untyped = [n for n in uses if n not in replacements]
289
+ if untyped_fallback:
290
+ for n in untyped:
291
+ replacements[n] = "(SELECT NULL)"
292
+ return Substitution(apply_values(sql, replacements), replacements, untyped)
293
+
294
+
295
+ def apply_values(sql: str, values: dict[int, str]) -> str:
296
+ """Replace each $n that has a value; placeholders inside literals, comments and identifiers stay."""
297
+ return _apply(sql, mask_sql(sql), values)
298
+
299
+
300
+ def _rewrite_typed_literals(sql: str, masked: str) -> str:
301
+ out, last = [], 0
302
+ for m in _TYPED_LITERAL.finditer(masked):
303
+ out += [sql[last:m.start()], f"CAST(${m.group(2)} AS {m.group(1)})"]
304
+ last = m.end()
305
+ return "".join(out) + sql[last:]
306
+
307
+
308
+ def _apply(sql: str, masked: str, replacements: dict[int, str]) -> str:
309
+ """Replace placeholders found in code only; literals, comments and identifiers stay untouched."""
310
+ spans = [(m.start(), m.end(), int(m.group(2))) for m in _TYPED_LITERAL.finditer(masked)]
311
+ for m in _PARAM.finditer(masked):
312
+ if not any(s <= m.start() < e for s, e, _ in spans):
313
+ spans.append((m.start(), m.end(), int(m.group(1))))
314
+ out, last = [], 0
315
+ for start, end, n in sorted(spans):
316
+ if n in replacements:
317
+ out += [sql[last:start], replacements[n]]
318
+ last = end
319
+ out.append(sql[last:])
320
+ return "".join(out)