mysqlslowlog 0.2.3__tar.gz
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.
- mysqlslowlog-0.2.3/LICENSE +29 -0
- mysqlslowlog-0.2.3/PKG-INFO +88 -0
- mysqlslowlog-0.2.3/README.md +64 -0
- mysqlslowlog-0.2.3/pyproject.toml +40 -0
- mysqlslowlog-0.2.3/setup.cfg +4 -0
- mysqlslowlog-0.2.3/src/mysqlslowlog/__init__.py +6 -0
- mysqlslowlog-0.2.3/src/mysqlslowlog/reader.py +249 -0
- mysqlslowlog-0.2.3/src/mysqlslowlog/sql/__init__.py +7 -0
- mysqlslowlog-0.2.3/src/mysqlslowlog/sql/digest.py +26 -0
- mysqlslowlog-0.2.3/src/mysqlslowlog/sql/parser.py +47 -0
- mysqlslowlog-0.2.3/src/mysqlslowlog/sql/types.py +22 -0
- mysqlslowlog-0.2.3/src/mysqlslowlog.egg-info/PKG-INFO +88 -0
- mysqlslowlog-0.2.3/src/mysqlslowlog.egg-info/SOURCES.txt +14 -0
- mysqlslowlog-0.2.3/src/mysqlslowlog.egg-info/dependency_links.txt +1 -0
- mysqlslowlog-0.2.3/src/mysqlslowlog.egg-info/requires.txt +6 -0
- mysqlslowlog-0.2.3/src/mysqlslowlog.egg-info/top_level.txt +1 -0
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
BSD 3-Clause License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2022-2026, pavlozt
|
|
4
|
+
All rights reserved.
|
|
5
|
+
|
|
6
|
+
Redistribution and use in source and binary forms, with or without
|
|
7
|
+
modification, are permitted provided that the following conditions are met:
|
|
8
|
+
|
|
9
|
+
1. Redistributions of source code must retain the above copyright notice, this
|
|
10
|
+
list of conditions and the following disclaimer.
|
|
11
|
+
|
|
12
|
+
2. Redistributions in binary form must reproduce the above copyright notice,
|
|
13
|
+
this list of conditions and the following disclaimer in the documentation
|
|
14
|
+
and/or other materials provided with the distribution.
|
|
15
|
+
|
|
16
|
+
3. Neither the name of the copyright holder nor the names of its
|
|
17
|
+
contributors may be used to endorse or promote products derived from
|
|
18
|
+
this software without specific prior written permission.
|
|
19
|
+
|
|
20
|
+
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
|
|
21
|
+
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
|
|
22
|
+
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
|
|
23
|
+
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
|
|
24
|
+
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
|
|
25
|
+
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
|
|
26
|
+
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
|
|
27
|
+
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
|
|
28
|
+
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
|
|
29
|
+
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
|
@@ -0,0 +1,88 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: mysqlslowlog
|
|
3
|
+
Version: 0.2.3
|
|
4
|
+
Summary: Read and process MySQL slow query logs
|
|
5
|
+
Author-email: Pavel Z <pwlonw@gmail.com>
|
|
6
|
+
License-Expression: BSD-3-Clause
|
|
7
|
+
Project-URL: Homepage, https://github.com/pavlozt/py-mysql-slowlog
|
|
8
|
+
Project-URL: Repository, https://github.com/pavlozt/py-mysql-slowlog
|
|
9
|
+
Project-URL: Issues, https://github.com/pavlozt/py-mysql-slowlog/issues
|
|
10
|
+
Classifier: Programming Language :: Python :: 3
|
|
11
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
12
|
+
Classifier: Topic :: Database
|
|
13
|
+
Classifier: Topic :: Text Processing :: Filters
|
|
14
|
+
Classifier: Operating System :: OS Independent
|
|
15
|
+
Requires-Python: >=3.11
|
|
16
|
+
Description-Content-Type: text/markdown
|
|
17
|
+
License-File: LICENSE
|
|
18
|
+
Requires-Dist: pandas>=2.0
|
|
19
|
+
Provides-Extra: dev
|
|
20
|
+
Requires-Dist: pytest>=8.0; extra == "dev"
|
|
21
|
+
Requires-Dist: pytest-sugar>=1.0; extra == "dev"
|
|
22
|
+
Requires-Dist: pytest-cov>=7.1.0; extra == "dev"
|
|
23
|
+
Dynamic: license-file
|
|
24
|
+
|
|
25
|
+
# MysqlSlowLog
|
|
26
|
+
|
|
27
|
+
Transform MySQL slow query logs into actionable pandas data - find the costliest queries, explore latency patterns, and visualize database bottlenecks with statistical precision.
|
|
28
|
+
|
|
29
|
+
[](https://github.com/pavlozt/py-mysql-slowlog/actions/workflows/tests.yaml)
|
|
30
|
+
|
|
31
|
+
## Usage
|
|
32
|
+
|
|
33
|
+
Download a log file from the server and use it as a `DataFrame`:
|
|
34
|
+
|
|
35
|
+
```python
|
|
36
|
+
import mysqlslowlog
|
|
37
|
+
|
|
38
|
+
df = mysqlslowlog.read(
|
|
39
|
+
'tests/integration/data/mariadb10.3/4_bigger.slow.log.gz',
|
|
40
|
+
save_sql=False,
|
|
41
|
+
)
|
|
42
|
+
|
|
43
|
+
# Queries that took longer than 1 second and examined more than 100,000 rows
|
|
44
|
+
bigq = df.loc[(df["query_time"] > 1) & (df["rows_examined"] > 100_000)]
|
|
45
|
+
print(bigq.head(3))
|
|
46
|
+
|
|
47
|
+
# 95th percentile of query times for queries that used a temporary table on disk
|
|
48
|
+
disk_tmp = df.loc[df["tmp_table_on_disk"]]
|
|
49
|
+
p95 = disk_tmp["query_time"].quantile(0.95)
|
|
50
|
+
print(f"p95 query_time: {p95:.3f}")
|
|
51
|
+
```
|
|
52
|
+
|
|
53
|
+
## Other examples
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
- [Disk sort investigation](https://github.com/pavlozt/py-mysql-slowlog/blob/master/examples/bytesort_investigation_example.ipynb) — analysis of disk sorting and temporary table usage.
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
## Installation
|
|
60
|
+
|
|
61
|
+
### Install from PyPI
|
|
62
|
+
|
|
63
|
+
```bash
|
|
64
|
+
pip install mysqlslowlog
|
|
65
|
+
```
|
|
66
|
+
|
|
67
|
+
### Install directly from Git
|
|
68
|
+
|
|
69
|
+
```bash
|
|
70
|
+
python -m pip install "git+https://github.com/pavlozt/py-mysql-slowlog.git"
|
|
71
|
+
```
|
|
72
|
+
|
|
73
|
+
## Development and testing
|
|
74
|
+
|
|
75
|
+
Python 3.11+ is required. Create and activate a virtual environment, then install the project and development dependencies:
|
|
76
|
+
|
|
77
|
+
```bash
|
|
78
|
+
python -m venv .venv
|
|
79
|
+
source .venv/bin/activate
|
|
80
|
+
python -m pip install -e '.[dev]'
|
|
81
|
+
```
|
|
82
|
+
|
|
83
|
+
Run all unit and integration tests:
|
|
84
|
+
|
|
85
|
+
```bash
|
|
86
|
+
python -m pytest
|
|
87
|
+
```
|
|
88
|
+
|
|
@@ -0,0 +1,64 @@
|
|
|
1
|
+
# MysqlSlowLog
|
|
2
|
+
|
|
3
|
+
Transform MySQL slow query logs into actionable pandas data - find the costliest queries, explore latency patterns, and visualize database bottlenecks with statistical precision.
|
|
4
|
+
|
|
5
|
+
[](https://github.com/pavlozt/py-mysql-slowlog/actions/workflows/tests.yaml)
|
|
6
|
+
|
|
7
|
+
## Usage
|
|
8
|
+
|
|
9
|
+
Download a log file from the server and use it as a `DataFrame`:
|
|
10
|
+
|
|
11
|
+
```python
|
|
12
|
+
import mysqlslowlog
|
|
13
|
+
|
|
14
|
+
df = mysqlslowlog.read(
|
|
15
|
+
'tests/integration/data/mariadb10.3/4_bigger.slow.log.gz',
|
|
16
|
+
save_sql=False,
|
|
17
|
+
)
|
|
18
|
+
|
|
19
|
+
# Queries that took longer than 1 second and examined more than 100,000 rows
|
|
20
|
+
bigq = df.loc[(df["query_time"] > 1) & (df["rows_examined"] > 100_000)]
|
|
21
|
+
print(bigq.head(3))
|
|
22
|
+
|
|
23
|
+
# 95th percentile of query times for queries that used a temporary table on disk
|
|
24
|
+
disk_tmp = df.loc[df["tmp_table_on_disk"]]
|
|
25
|
+
p95 = disk_tmp["query_time"].quantile(0.95)
|
|
26
|
+
print(f"p95 query_time: {p95:.3f}")
|
|
27
|
+
```
|
|
28
|
+
|
|
29
|
+
## Other examples
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
- [Disk sort investigation](https://github.com/pavlozt/py-mysql-slowlog/blob/master/examples/bytesort_investigation_example.ipynb) — analysis of disk sorting and temporary table usage.
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
## Installation
|
|
36
|
+
|
|
37
|
+
### Install from PyPI
|
|
38
|
+
|
|
39
|
+
```bash
|
|
40
|
+
pip install mysqlslowlog
|
|
41
|
+
```
|
|
42
|
+
|
|
43
|
+
### Install directly from Git
|
|
44
|
+
|
|
45
|
+
```bash
|
|
46
|
+
python -m pip install "git+https://github.com/pavlozt/py-mysql-slowlog.git"
|
|
47
|
+
```
|
|
48
|
+
|
|
49
|
+
## Development and testing
|
|
50
|
+
|
|
51
|
+
Python 3.11+ is required. Create and activate a virtual environment, then install the project and development dependencies:
|
|
52
|
+
|
|
53
|
+
```bash
|
|
54
|
+
python -m venv .venv
|
|
55
|
+
source .venv/bin/activate
|
|
56
|
+
python -m pip install -e '.[dev]'
|
|
57
|
+
```
|
|
58
|
+
|
|
59
|
+
Run all unit and integration tests:
|
|
60
|
+
|
|
61
|
+
```bash
|
|
62
|
+
python -m pytest
|
|
63
|
+
```
|
|
64
|
+
|
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
[build-system]
|
|
2
|
+
requires = ["setuptools>=77.0.3"]
|
|
3
|
+
build-backend = "setuptools.build_meta"
|
|
4
|
+
|
|
5
|
+
[project]
|
|
6
|
+
name = "mysqlslowlog"
|
|
7
|
+
version = "0.2.3"
|
|
8
|
+
authors = [
|
|
9
|
+
{ name="Pavel Z", email="pwlonw@gmail.com" },
|
|
10
|
+
]
|
|
11
|
+
description = "Read and process MySQL slow query logs"
|
|
12
|
+
readme = "README.md"
|
|
13
|
+
requires-python = ">=3.11"
|
|
14
|
+
license = "BSD-3-Clause"
|
|
15
|
+
license-files = ["LICENSE"]
|
|
16
|
+
dependencies = ["pandas>=2.0"]
|
|
17
|
+
classifiers = [
|
|
18
|
+
"Programming Language :: Python :: 3",
|
|
19
|
+
"Programming Language :: Python :: 3.11",
|
|
20
|
+
"Topic :: Database",
|
|
21
|
+
"Topic :: Text Processing :: Filters",
|
|
22
|
+
"Operating System :: OS Independent",
|
|
23
|
+
]
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
[project.urls]
|
|
27
|
+
Homepage = "https://github.com/pavlozt/py-mysql-slowlog"
|
|
28
|
+
Repository = "https://github.com/pavlozt/py-mysql-slowlog"
|
|
29
|
+
Issues = "https://github.com/pavlozt/py-mysql-slowlog/issues"
|
|
30
|
+
|
|
31
|
+
[project.optional-dependencies]
|
|
32
|
+
dev = ["pytest>=8.0", "pytest-sugar>=1.0", "pytest-cov>=7.1.0"]
|
|
33
|
+
|
|
34
|
+
[tool.setuptools.packages.find]
|
|
35
|
+
where = ["src"]
|
|
36
|
+
|
|
37
|
+
[tool.pytest.ini_options]
|
|
38
|
+
testpaths = ["tests"]
|
|
39
|
+
pythonpath = ["src"]
|
|
40
|
+
addopts = ["-p", "no:libtmux", "--ignore=tests/integration/pt-query-digest"]
|
|
@@ -0,0 +1,249 @@
|
|
|
1
|
+
"""Read MySQL slow-log files into pandas objects."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import gzip
|
|
6
|
+
import re
|
|
7
|
+
from datetime import datetime
|
|
8
|
+
from pathlib import Path
|
|
9
|
+
from typing import Iterator, TextIO
|
|
10
|
+
|
|
11
|
+
import pandas as pd
|
|
12
|
+
|
|
13
|
+
READ_CHUNK_SIZE = 65_536
|
|
14
|
+
|
|
15
|
+
# Output columns are grouped by their resulting pandas type. For example, a
|
|
16
|
+
# slow-log entry can contain a timestamp, schema and SQL statement (strings),
|
|
17
|
+
# Rows_sent (integer), Query_time (float), and Full_scan (boolean).
|
|
18
|
+
COLUMN_NAMES_TIMESTAMP = ["timestamp"]
|
|
19
|
+
COLUMN_NAMES_STRING = ["schema", "sqltext"]
|
|
20
|
+
COLUMN_NAMES_INTEGER = [
|
|
21
|
+
"rows_sent",
|
|
22
|
+
"rows_examined",
|
|
23
|
+
"rows_affected",
|
|
24
|
+
"bytes_sent",
|
|
25
|
+
"tmp_table_sizes",
|
|
26
|
+
"tmp_tables",
|
|
27
|
+
"tmp_disk_tables",
|
|
28
|
+
"merge_passes",
|
|
29
|
+
]
|
|
30
|
+
COLUMN_NAMES_FLOAT = ["query_time", "lock_time"]
|
|
31
|
+
COLUMN_NAMES_BOOLEAN = [
|
|
32
|
+
"full_scan",
|
|
33
|
+
"full_join",
|
|
34
|
+
"tmp_table",
|
|
35
|
+
"tmp_table_on_disk",
|
|
36
|
+
"filesort",
|
|
37
|
+
"filesort_on_disk",
|
|
38
|
+
]
|
|
39
|
+
# Keep a stable DataFrame column order by combining the typed groups above.
|
|
40
|
+
COLUMN_NAMES = (
|
|
41
|
+
COLUMN_NAMES_TIMESTAMP
|
|
42
|
+
+ COLUMN_NAMES_STRING
|
|
43
|
+
+ COLUMN_NAMES_INTEGER
|
|
44
|
+
+ COLUMN_NAMES_FLOAT
|
|
45
|
+
+ COLUMN_NAMES_BOOLEAN
|
|
46
|
+
)
|
|
47
|
+
|
|
48
|
+
# Stat keys include output columns plus common slow-log metadata. For example,
|
|
49
|
+
# a Thread_id / Schema / QC_hit line contains metadata; stats lines use keys
|
|
50
|
+
# such as Query_time and Rows_sent.
|
|
51
|
+
_STAT_KEYS = set(COLUMN_NAMES) | {
|
|
52
|
+
"user@host",
|
|
53
|
+
"thread_id",
|
|
54
|
+
"qc_hit",
|
|
55
|
+
"id",
|
|
56
|
+
"priority_queue",
|
|
57
|
+
}
|
|
58
|
+
# Accept spaces or underscores in property names (e.g. Rows sent / Rows_sent).
|
|
59
|
+
_STAT_KEY_PATTERN = "|".join(
|
|
60
|
+
re.escape(key).replace("_", r"[\s_]+")
|
|
61
|
+
for key in sorted(_STAT_KEYS, key=len, reverse=True)
|
|
62
|
+
)
|
|
63
|
+
# Capture each key/value pair up to the next recognized key or end of line.
|
|
64
|
+
_STAT_LINE = re.compile(
|
|
65
|
+
rf"(?P<key>{_STAT_KEY_PATTERN}):\s*"
|
|
66
|
+
rf"(?P<value>.*?)(?=\s+(?:{_STAT_KEY_PATTERN}):\s*|$)",
|
|
67
|
+
re.IGNORECASE,
|
|
68
|
+
)
|
|
69
|
+
# ISO-form timestamp example: `# Time: 2026-11-28T21:05:44.287256Z`.
|
|
70
|
+
_ISO_TIME = re.compile(r"^#\s*Time:\s*(\d{4}-\d{2}-\d{2}T[^\s]+)", re.MULTILINE)
|
|
71
|
+
# Legacy timestamp example: `# Time: 220716 0:00:02`.
|
|
72
|
+
_LEGACY_TIME = re.compile(r"^#\s*Time:\s*(\d{6})\s+(\d{1,2}:\d{2}:\d{2})", re.MULTILINE)
|
|
73
|
+
# Schema is usually present in a comment line alongside Thread_id and QC_hit.
|
|
74
|
+
_SCHEMA_LINE = re.compile(r"(?:^|\s)Schema:\s*([^\s]+)", re.MULTILINE)
|
|
75
|
+
# Ignore the USE database directive and MySQL's per-query timestamp directive
|
|
76
|
+
# when collecting SQL text. They are log metadata, not query statements.
|
|
77
|
+
_USE_DATABASE = re.compile(r"^[ \t]*use\s+[^;]+;[ \t]*", re.IGNORECASE | re.MULTILINE)
|
|
78
|
+
_SET_TIMESTAMP = re.compile(r"^[ \t]*SET\s+timestamp\s*=\s*\d+;[ \t]*", re.IGNORECASE | re.MULTILINE)
|
|
79
|
+
_SET_TIMESTAMP_VALUE = re.compile(r"^[ \t]*SET\s+timestamp\s*=\s*(\d+);", re.IGNORECASE | re.MULTILINE)
|
|
80
|
+
_SET_TIMESTAMP_LINE = re.compile(r"(?m)^[ \t]*SET\s+timestamp\s*=\s*\d+;[ \t]*")
|
|
81
|
+
_USER_HOST_LINE = re.compile(r"(?m)^#\s*User@Host:")
|
|
82
|
+
_TECHNICAL_PROPERTIES = {"user@host", "thread_id"}
|
|
83
|
+
_TIME_BLOCK_DELIMITER = "\n# Time:"
|
|
84
|
+
|
|
85
|
+
|
|
86
|
+
def _iter_delimited_text(stream: TextIO, delimiter: str) -> Iterator[str]:
|
|
87
|
+
"""Yield text chunks split by an exact delimiter."""
|
|
88
|
+
buf = ""
|
|
89
|
+
while True:
|
|
90
|
+
while delimiter in buf:
|
|
91
|
+
pos = buf.index(delimiter)
|
|
92
|
+
yield buf[:pos]
|
|
93
|
+
buf = buf[pos + len(delimiter):]
|
|
94
|
+
chunk = stream.read(READ_CHUNK_SIZE)
|
|
95
|
+
if not chunk:
|
|
96
|
+
if buf:
|
|
97
|
+
yield buf
|
|
98
|
+
break
|
|
99
|
+
buf += chunk
|
|
100
|
+
|
|
101
|
+
|
|
102
|
+
def _open_slow_log(filename: str | Path) -> TextIO:
|
|
103
|
+
path = Path(filename)
|
|
104
|
+
if path.suffix.casefold() == ".gz":
|
|
105
|
+
return gzip.open(path, "rt", encoding="utf-8")
|
|
106
|
+
return path.open("rt", encoding="utf-8")
|
|
107
|
+
|
|
108
|
+
|
|
109
|
+
def _parse_timestamp(block: str) -> pd.Timestamp | None:
|
|
110
|
+
iso_match = _ISO_TIME.search(block)
|
|
111
|
+
if iso_match:
|
|
112
|
+
# MySQL 8 writes UTC timestamps; return a timezone-naive UTC value.
|
|
113
|
+
return pd.to_datetime(iso_match.group(1), utc=True).tz_localize(None)
|
|
114
|
+
|
|
115
|
+
legacy_match = _LEGACY_TIME.search(block)
|
|
116
|
+
if not legacy_match:
|
|
117
|
+
return None
|
|
118
|
+
|
|
119
|
+
date_text = legacy_match.group(1)
|
|
120
|
+
time_text = legacy_match.group(2)
|
|
121
|
+
year = 2000 + int(date_text[:2])
|
|
122
|
+
month = int(date_text[2:4])
|
|
123
|
+
day = int(date_text[4:6])
|
|
124
|
+
hour, minute, second = (int(part) for part in time_text.split(":"))
|
|
125
|
+
return pd.Timestamp(datetime(year, month, day, hour, minute, second))
|
|
126
|
+
|
|
127
|
+
|
|
128
|
+
def _parse_unix_timestamp(block: str, offset: pd.Timedelta = pd.Timedelta(0)) -> pd.Timestamp | None:
|
|
129
|
+
"""Parse SET timestamp and align it to the timezone shown by # Time."""
|
|
130
|
+
match = _SET_TIMESTAMP_VALUE.search(block)
|
|
131
|
+
if not match:
|
|
132
|
+
return None
|
|
133
|
+
try:
|
|
134
|
+
timestamp = pd.to_datetime(int(match.group(1)), unit="s", utc=True).tz_localize(None)
|
|
135
|
+
except (OverflowError, ValueError):
|
|
136
|
+
return None
|
|
137
|
+
return timestamp + offset
|
|
138
|
+
|
|
139
|
+
|
|
140
|
+
def _timestamp_offset(block: str) -> pd.Timedelta:
|
|
141
|
+
"""Match Unix SET timestamps to the slow-log server's displayed timezone."""
|
|
142
|
+
displayed = _parse_timestamp(block)
|
|
143
|
+
unix = _parse_unix_timestamp(block)
|
|
144
|
+
if displayed is None or unix is None:
|
|
145
|
+
return pd.Timedelta(0)
|
|
146
|
+
return displayed - unix
|
|
147
|
+
|
|
148
|
+
|
|
149
|
+
def _split_sql(block: str) -> str:
|
|
150
|
+
lines = block.splitlines()
|
|
151
|
+
sql_lines = [line for line in lines if not line.startswith("#")]
|
|
152
|
+
sql = "\n".join(sql_lines).strip()
|
|
153
|
+
sql = _USE_DATABASE.sub("", sql)
|
|
154
|
+
sql = _SET_TIMESTAMP.sub("", sql)
|
|
155
|
+
return sql.strip()
|
|
156
|
+
|
|
157
|
+
|
|
158
|
+
def _parse_properties(block: str) -> dict[str, str]:
|
|
159
|
+
properties: dict[str, str] = {}
|
|
160
|
+
for line in block.splitlines():
|
|
161
|
+
if not line.startswith("#"):
|
|
162
|
+
continue
|
|
163
|
+
for match in _STAT_LINE.finditer(line[1:].strip()):
|
|
164
|
+
key = re.sub(r"\s+", "_", match.group("key").strip().lower())
|
|
165
|
+
if key not in _TECHNICAL_PROPERTIES:
|
|
166
|
+
properties[key] = match.group("value").strip()
|
|
167
|
+
return properties
|
|
168
|
+
|
|
169
|
+
|
|
170
|
+
def _iter_sql_events(block: str) -> Iterator[str]:
|
|
171
|
+
"""Split a time block into records using event headers or SET timestamps."""
|
|
172
|
+
user_headers = [match.start() for match in _USER_HOST_LINE.finditer(block)]
|
|
173
|
+
if len(user_headers) > 1:
|
|
174
|
+
starts = [0, *user_headers[1:]]
|
|
175
|
+
else:
|
|
176
|
+
set_timestamps = [match.start() for match in _SET_TIMESTAMP_LINE.finditer(block)]
|
|
177
|
+
if len(set_timestamps) < 2:
|
|
178
|
+
yield block
|
|
179
|
+
return
|
|
180
|
+
# Some MariaDB logs omit repeated User@Host headers. In those blocks,
|
|
181
|
+
# each SET timestamp marks the next SQL event.
|
|
182
|
+
starts = [0, *set_timestamps[1:]]
|
|
183
|
+
|
|
184
|
+
for index, start in enumerate(starts):
|
|
185
|
+
end = starts[index + 1] if index + 1 < len(starts) else len(block)
|
|
186
|
+
yield block[start:end].rstrip()
|
|
187
|
+
|
|
188
|
+
|
|
189
|
+
def _record_from_block(
|
|
190
|
+
block: str, save_sql: bool, timestamp_offset: pd.Timedelta = pd.Timedelta(0)
|
|
191
|
+
) -> dict[str, object] | None:
|
|
192
|
+
timestamp = _parse_unix_timestamp(block, timestamp_offset) or _parse_timestamp(block)
|
|
193
|
+
if timestamp is None:
|
|
194
|
+
return None
|
|
195
|
+
|
|
196
|
+
record: dict[str, object] = _parse_properties(block)
|
|
197
|
+
record["timestamp"] = timestamp
|
|
198
|
+
|
|
199
|
+
schema_match = _SCHEMA_LINE.search(block)
|
|
200
|
+
if schema_match:
|
|
201
|
+
record["schema"] = schema_match.group(1)
|
|
202
|
+
else:
|
|
203
|
+
sql = _split_sql(block)
|
|
204
|
+
use_match = re.search(r"^use\s+([^;]+);", sql, re.IGNORECASE | re.MULTILINE)
|
|
205
|
+
if use_match:
|
|
206
|
+
record["schema"] = use_match.group(1).strip()
|
|
207
|
+
|
|
208
|
+
sql = _split_sql(block)
|
|
209
|
+
if not sql:
|
|
210
|
+
return None
|
|
211
|
+
record["sqltext"] = sql if save_sql else ""
|
|
212
|
+
return record
|
|
213
|
+
|
|
214
|
+
|
|
215
|
+
def read(filename: str | Path, save_sql: bool = True) -> pd.DataFrame:
|
|
216
|
+
"""Read a MySQL slow-log file or gzip file into a pandas DataFrame."""
|
|
217
|
+
data = {name: [] for name in COLUMN_NAMES}
|
|
218
|
+
|
|
219
|
+
with _open_slow_log(filename) as stream:
|
|
220
|
+
for block_number, block in enumerate(
|
|
221
|
+
_iter_delimited_text(stream, _TIME_BLOCK_DELIMITER)
|
|
222
|
+
):
|
|
223
|
+
# The splitter consumes the delimiter; restore the next block's
|
|
224
|
+
# header so timestamp parsing sees the same format as the first.
|
|
225
|
+
if block_number:
|
|
226
|
+
block = "# Time:" + block
|
|
227
|
+
offset = _timestamp_offset(block)
|
|
228
|
+
|
|
229
|
+
for event in _iter_sql_events(block):
|
|
230
|
+
record = _record_from_block(event, save_sql, offset)
|
|
231
|
+
if record is None:
|
|
232
|
+
continue
|
|
233
|
+
for name in COLUMN_NAMES:
|
|
234
|
+
data[name].append(record.get(name))
|
|
235
|
+
|
|
236
|
+
frame = pd.DataFrame.from_dict(data)
|
|
237
|
+
|
|
238
|
+
bool_replace_map = {"No": False, "False": False, "Yes": True, "True": True}
|
|
239
|
+
for name in COLUMN_NAMES_BOOLEAN:
|
|
240
|
+
frame[name] = frame[name].map(bool_replace_map).fillna(False).astype("bool")
|
|
241
|
+
|
|
242
|
+
for name in COLUMN_NAMES_FLOAT:
|
|
243
|
+
frame[name] = pd.to_numeric(frame[name], errors="coerce").astype("float64")
|
|
244
|
+
|
|
245
|
+
for name in COLUMN_NAMES_INTEGER:
|
|
246
|
+
frame[name] = pd.to_numeric(frame[name], errors="coerce").fillna(0).astype("int64")
|
|
247
|
+
|
|
248
|
+
frame["timestamp"] = pd.to_datetime(frame["timestamp"], errors="coerce")
|
|
249
|
+
return frame
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
"""Build per-call digest records from SQL statements."""
|
|
2
|
+
|
|
3
|
+
from collections.abc import Iterable
|
|
4
|
+
|
|
5
|
+
from .parser import parse_sql
|
|
6
|
+
from .types import QueryDigest
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
def build_digests(queries: Iterable[str]) -> list[QueryDigest]:
|
|
10
|
+
"""Group equivalent normalized statements into digest rows."""
|
|
11
|
+
records: dict[tuple[str, str], QueryDigest] = {}
|
|
12
|
+
|
|
13
|
+
for sql in queries:
|
|
14
|
+
analysis = parse_sql(sql)
|
|
15
|
+
key = (analysis.statement_type, analysis.normalized_sql)
|
|
16
|
+
digest = records.get(key)
|
|
17
|
+
if digest is None:
|
|
18
|
+
records[key] = QueryDigest(
|
|
19
|
+
normalized_sql=analysis.normalized_sql,
|
|
20
|
+
statement_type=analysis.statement_type,
|
|
21
|
+
touched_tables=analysis.touched_tables,
|
|
22
|
+
)
|
|
23
|
+
else:
|
|
24
|
+
digest.count += 1
|
|
25
|
+
|
|
26
|
+
return list(records.values())
|
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
"""Minimal SQL classification, designed to be replaceable by a parser."""
|
|
2
|
+
|
|
3
|
+
import re
|
|
4
|
+
|
|
5
|
+
from .types import SQLAnalysis
|
|
6
|
+
|
|
7
|
+
_STATEMENT_TYPES = {"select", "insert", "update", "delete", "replace"}
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
def _statement_keyword(sql: str) -> str:
|
|
11
|
+
match = re.match(r"([A-Za-z]+)\b", sql)
|
|
12
|
+
if match is None:
|
|
13
|
+
return ""
|
|
14
|
+
|
|
15
|
+
keyword = match.group(1).casefold()
|
|
16
|
+
if keyword != "with":
|
|
17
|
+
return keyword
|
|
18
|
+
|
|
19
|
+
# Skip CTE bodies and find the main statement at parenthesis depth zero.
|
|
20
|
+
depth = 0
|
|
21
|
+
for token in re.finditer(r"\(|\)|[A-Za-z]+", sql[match.end():]):
|
|
22
|
+
value = token.group(0)
|
|
23
|
+
if value == "(":
|
|
24
|
+
depth += 1
|
|
25
|
+
elif value == ")":
|
|
26
|
+
depth = max(0, depth - 1)
|
|
27
|
+
elif depth == 0 and value.casefold() in _STATEMENT_TYPES:
|
|
28
|
+
return value.casefold()
|
|
29
|
+
return "other"
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
def parse_sql(sql: str) -> SQLAnalysis:
|
|
33
|
+
"""Normalize whitespace and classify the leading SQL operation.
|
|
34
|
+
|
|
35
|
+
This is intentionally a small classifier, not a SQL grammar. CTE handling
|
|
36
|
+
only identifies the main operation after balanced CTE parentheses.
|
|
37
|
+
"""
|
|
38
|
+
if not isinstance(sql, str):
|
|
39
|
+
raise TypeError("sql must be a string")
|
|
40
|
+
|
|
41
|
+
normalized_sql = " ".join(sql.split())
|
|
42
|
+
if not normalized_sql:
|
|
43
|
+
raise ValueError("sql must not be empty")
|
|
44
|
+
|
|
45
|
+
keyword = _statement_keyword(normalized_sql)
|
|
46
|
+
statement_type = keyword if keyword in _STATEMENT_TYPES else "other"
|
|
47
|
+
return SQLAnalysis(normalized_sql=normalized_sql, statement_type=statement_type)
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
"""Interfaces for SQL analysis and digest records."""
|
|
2
|
+
|
|
3
|
+
from dataclasses import dataclass
|
|
4
|
+
|
|
5
|
+
|
|
6
|
+
@dataclass(frozen=True, slots=True)
|
|
7
|
+
class SQLAnalysis:
|
|
8
|
+
"""The normalized statement and future parser metadata."""
|
|
9
|
+
|
|
10
|
+
normalized_sql: str
|
|
11
|
+
statement_type: str
|
|
12
|
+
touched_tables: tuple[str, ...] = ()
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
@dataclass(slots=True)
|
|
16
|
+
class QueryDigest:
|
|
17
|
+
"""Aggregated record for equivalent SQL statements."""
|
|
18
|
+
|
|
19
|
+
normalized_sql: str
|
|
20
|
+
statement_type: str
|
|
21
|
+
touched_tables: tuple[str, ...] = ()
|
|
22
|
+
count: int = 1
|
|
@@ -0,0 +1,88 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: mysqlslowlog
|
|
3
|
+
Version: 0.2.3
|
|
4
|
+
Summary: Read and process MySQL slow query logs
|
|
5
|
+
Author-email: Pavel Z <pwlonw@gmail.com>
|
|
6
|
+
License-Expression: BSD-3-Clause
|
|
7
|
+
Project-URL: Homepage, https://github.com/pavlozt/py-mysql-slowlog
|
|
8
|
+
Project-URL: Repository, https://github.com/pavlozt/py-mysql-slowlog
|
|
9
|
+
Project-URL: Issues, https://github.com/pavlozt/py-mysql-slowlog/issues
|
|
10
|
+
Classifier: Programming Language :: Python :: 3
|
|
11
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
12
|
+
Classifier: Topic :: Database
|
|
13
|
+
Classifier: Topic :: Text Processing :: Filters
|
|
14
|
+
Classifier: Operating System :: OS Independent
|
|
15
|
+
Requires-Python: >=3.11
|
|
16
|
+
Description-Content-Type: text/markdown
|
|
17
|
+
License-File: LICENSE
|
|
18
|
+
Requires-Dist: pandas>=2.0
|
|
19
|
+
Provides-Extra: dev
|
|
20
|
+
Requires-Dist: pytest>=8.0; extra == "dev"
|
|
21
|
+
Requires-Dist: pytest-sugar>=1.0; extra == "dev"
|
|
22
|
+
Requires-Dist: pytest-cov>=7.1.0; extra == "dev"
|
|
23
|
+
Dynamic: license-file
|
|
24
|
+
|
|
25
|
+
# MysqlSlowLog
|
|
26
|
+
|
|
27
|
+
Transform MySQL slow query logs into actionable pandas data - find the costliest queries, explore latency patterns, and visualize database bottlenecks with statistical precision.
|
|
28
|
+
|
|
29
|
+
[](https://github.com/pavlozt/py-mysql-slowlog/actions/workflows/tests.yaml)
|
|
30
|
+
|
|
31
|
+
## Usage
|
|
32
|
+
|
|
33
|
+
Download a log file from the server and use it as a `DataFrame`:
|
|
34
|
+
|
|
35
|
+
```python
|
|
36
|
+
import mysqlslowlog
|
|
37
|
+
|
|
38
|
+
df = mysqlslowlog.read(
|
|
39
|
+
'tests/integration/data/mariadb10.3/4_bigger.slow.log.gz',
|
|
40
|
+
save_sql=False,
|
|
41
|
+
)
|
|
42
|
+
|
|
43
|
+
# Queries that took longer than 1 second and examined more than 100,000 rows
|
|
44
|
+
bigq = df.loc[(df["query_time"] > 1) & (df["rows_examined"] > 100_000)]
|
|
45
|
+
print(bigq.head(3))
|
|
46
|
+
|
|
47
|
+
# 95th percentile of query times for queries that used a temporary table on disk
|
|
48
|
+
disk_tmp = df.loc[df["tmp_table_on_disk"]]
|
|
49
|
+
p95 = disk_tmp["query_time"].quantile(0.95)
|
|
50
|
+
print(f"p95 query_time: {p95:.3f}")
|
|
51
|
+
```
|
|
52
|
+
|
|
53
|
+
## Other examples
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
- [Disk sort investigation](https://github.com/pavlozt/py-mysql-slowlog/blob/master/examples/bytesort_investigation_example.ipynb) — analysis of disk sorting and temporary table usage.
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
## Installation
|
|
60
|
+
|
|
61
|
+
### Install from PyPI
|
|
62
|
+
|
|
63
|
+
```bash
|
|
64
|
+
pip install mysqlslowlog
|
|
65
|
+
```
|
|
66
|
+
|
|
67
|
+
### Install directly from Git
|
|
68
|
+
|
|
69
|
+
```bash
|
|
70
|
+
python -m pip install "git+https://github.com/pavlozt/py-mysql-slowlog.git"
|
|
71
|
+
```
|
|
72
|
+
|
|
73
|
+
## Development and testing
|
|
74
|
+
|
|
75
|
+
Python 3.11+ is required. Create and activate a virtual environment, then install the project and development dependencies:
|
|
76
|
+
|
|
77
|
+
```bash
|
|
78
|
+
python -m venv .venv
|
|
79
|
+
source .venv/bin/activate
|
|
80
|
+
python -m pip install -e '.[dev]'
|
|
81
|
+
```
|
|
82
|
+
|
|
83
|
+
Run all unit and integration tests:
|
|
84
|
+
|
|
85
|
+
```bash
|
|
86
|
+
python -m pytest
|
|
87
|
+
```
|
|
88
|
+
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
LICENSE
|
|
2
|
+
README.md
|
|
3
|
+
pyproject.toml
|
|
4
|
+
src/mysqlslowlog/__init__.py
|
|
5
|
+
src/mysqlslowlog/reader.py
|
|
6
|
+
src/mysqlslowlog.egg-info/PKG-INFO
|
|
7
|
+
src/mysqlslowlog.egg-info/SOURCES.txt
|
|
8
|
+
src/mysqlslowlog.egg-info/dependency_links.txt
|
|
9
|
+
src/mysqlslowlog.egg-info/requires.txt
|
|
10
|
+
src/mysqlslowlog.egg-info/top_level.txt
|
|
11
|
+
src/mysqlslowlog/sql/__init__.py
|
|
12
|
+
src/mysqlslowlog/sql/digest.py
|
|
13
|
+
src/mysqlslowlog/sql/parser.py
|
|
14
|
+
src/mysqlslowlog/sql/types.py
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
mysqlslowlog
|