fastpluggy-postgres-tools 0.1.26__tar.gz → 0.1.37__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.
Potentially problematic release.
This version of fastpluggy-postgres-tools might be problematic. Click here for more details.
- {fastpluggy_postgres_tools-0.1.26 → fastpluggy_postgres_tools-0.1.37}/PKG-INFO +2 -5
- {fastpluggy_postgres_tools-0.1.26 → fastpluggy_postgres_tools-0.1.37}/README.md +0 -3
- {fastpluggy_postgres_tools-0.1.26 → fastpluggy_postgres_tools-0.1.37}/fastpluggy_postgres_tools.egg-info/PKG-INFO +2 -5
- {fastpluggy_postgres_tools-0.1.26 → fastpluggy_postgres_tools-0.1.37}/fastpluggy_postgres_tools.egg-info/SOURCES.txt +1 -0
- fastpluggy_postgres_tools-0.1.37/fastpluggy_postgres_tools.egg-info/requires.txt +2 -0
- {fastpluggy_postgres_tools-0.1.26 → fastpluggy_postgres_tools-0.1.37}/pyproject.toml +2 -2
- {fastpluggy_postgres_tools-0.1.26 → fastpluggy_postgres_tools-0.1.37}/src/plugin.py +16 -6
- {fastpluggy_postgres_tools-0.1.26 → fastpluggy_postgres_tools-0.1.37}/src/routers/alerts.py +4 -13
- {fastpluggy_postgres_tools-0.1.26 → fastpluggy_postgres_tools-0.1.37}/src/routers/connections.py +33 -20
- {fastpluggy_postgres_tools-0.1.26 → fastpluggy_postgres_tools-0.1.37}/src/routers/dashboard.py +180 -70
- {fastpluggy_postgres_tools-0.1.26 → fastpluggy_postgres_tools-0.1.37}/src/routers/db_size.py +6 -9
- {fastpluggy_postgres_tools-0.1.26 → fastpluggy_postgres_tools-0.1.37}/src/routers/extensions.py +0 -6
- {fastpluggy_postgres_tools-0.1.26 → fastpluggy_postgres_tools-0.1.37}/src/routers/indexes.py +8 -8
- {fastpluggy_postgres_tools-0.1.26 → fastpluggy_postgres_tools-0.1.37}/src/routers/queries.py +48 -49
- {fastpluggy_postgres_tools-0.1.26 → fastpluggy_postgres_tools-0.1.37}/src/routers/replication.py +4 -11
- {fastpluggy_postgres_tools-0.1.26 → fastpluggy_postgres_tools-0.1.37}/src/routers/sequences.py +0 -6
- {fastpluggy_postgres_tools-0.1.26 → fastpluggy_postgres_tools-0.1.37}/src/routers/tables.py +10 -10
- {fastpluggy_postgres_tools-0.1.26 → fastpluggy_postgres_tools-0.1.37}/src/routers/vacuum.py +10 -8
- fastpluggy_postgres_tools-0.1.37/src/templates/dashboard_cards.html.j2 +46 -0
- fastpluggy_postgres_tools-0.1.37/src/utils/__init__.py +23 -0
- {fastpluggy_postgres_tools-0.1.26 → fastpluggy_postgres_tools-0.1.37}/src/utils/db_utils.py +94 -0
- fastpluggy_postgres_tools-0.1.26/fastpluggy_postgres_tools.egg-info/requires.txt +0 -2
- fastpluggy_postgres_tools-0.1.26/src/utils/__init__.py +0 -11
- {fastpluggy_postgres_tools-0.1.26 → fastpluggy_postgres_tools-0.1.37}/fastpluggy_postgres_tools.egg-info/dependency_links.txt +0 -0
- {fastpluggy_postgres_tools-0.1.26 → fastpluggy_postgres_tools-0.1.37}/fastpluggy_postgres_tools.egg-info/entry_points.txt +0 -0
- {fastpluggy_postgres_tools-0.1.26 → fastpluggy_postgres_tools-0.1.37}/fastpluggy_postgres_tools.egg-info/top_level.txt +0 -0
- {fastpluggy_postgres_tools-0.1.26 → fastpluggy_postgres_tools-0.1.37}/setup.cfg +0 -0
- {fastpluggy_postgres_tools-0.1.26 → fastpluggy_postgres_tools-0.1.37}/src/__init__.py +0 -0
- {fastpluggy_postgres_tools-0.1.26 → fastpluggy_postgres_tools-0.1.37}/src/routers/__init__.py +0 -0
|
@@ -1,12 +1,12 @@
|
|
|
1
1
|
Metadata-Version: 2.4
|
|
2
2
|
Name: fastpluggy-postgres-tools
|
|
3
|
-
Version: 0.1.
|
|
3
|
+
Version: 0.1.37
|
|
4
4
|
Summary: PostgreSQL database monitoring and management plugin for FastPluggy
|
|
5
5
|
License-Expression: MIT
|
|
6
6
|
Requires-Python: >=3.10
|
|
7
7
|
Description-Content-Type: text/markdown
|
|
8
|
+
Requires-Dist: FastPluggy>=0.4.9
|
|
8
9
|
Requires-Dist: sqlalchemy>=2.0.0
|
|
9
|
-
Requires-Dist: fastpluggy-ui-tools>=0.0.4
|
|
10
10
|
|
|
11
11
|
# Postgres Tools for FastPluggy
|
|
12
12
|
|
|
@@ -18,8 +18,6 @@ This plugin provides a user-friendly interface to monitor and manage various asp
|
|
|
18
18
|
|
|
19
19
|
## Features
|
|
20
20
|
|
|
21
|
-
### Implemented Features
|
|
22
|
-
|
|
23
21
|
- **PostgreSQL Sequences Monitoring**:
|
|
24
22
|
- View comprehensive sequence information including name, last value, max value, and remaining capacity
|
|
25
23
|
- Monitor sequence usage with percentage metrics (percent used and percent remaining)
|
|
@@ -94,7 +92,6 @@ This plugin provides a user-friendly interface to monitor and manage various asp
|
|
|
94
92
|
- Database configuration recommendations
|
|
95
93
|
- Key metrics summary
|
|
96
94
|
|
|
97
|
-
### Planned Features
|
|
98
95
|
|
|
99
96
|
For detailed specifications of each feature, see the individual files in the `docs/feature/` directory.
|
|
100
97
|
|
|
@@ -8,8 +8,6 @@ This plugin provides a user-friendly interface to monitor and manage various asp
|
|
|
8
8
|
|
|
9
9
|
## Features
|
|
10
10
|
|
|
11
|
-
### Implemented Features
|
|
12
|
-
|
|
13
11
|
- **PostgreSQL Sequences Monitoring**:
|
|
14
12
|
- View comprehensive sequence information including name, last value, max value, and remaining capacity
|
|
15
13
|
- Monitor sequence usage with percentage metrics (percent used and percent remaining)
|
|
@@ -84,7 +82,6 @@ This plugin provides a user-friendly interface to monitor and manage various asp
|
|
|
84
82
|
- Database configuration recommendations
|
|
85
83
|
- Key metrics summary
|
|
86
84
|
|
|
87
|
-
### Planned Features
|
|
88
85
|
|
|
89
86
|
For detailed specifications of each feature, see the individual files in the `docs/feature/` directory.
|
|
90
87
|
|
|
@@ -1,12 +1,12 @@
|
|
|
1
1
|
Metadata-Version: 2.4
|
|
2
2
|
Name: fastpluggy-postgres-tools
|
|
3
|
-
Version: 0.1.
|
|
3
|
+
Version: 0.1.37
|
|
4
4
|
Summary: PostgreSQL database monitoring and management plugin for FastPluggy
|
|
5
5
|
License-Expression: MIT
|
|
6
6
|
Requires-Python: >=3.10
|
|
7
7
|
Description-Content-Type: text/markdown
|
|
8
|
+
Requires-Dist: FastPluggy>=0.4.9
|
|
8
9
|
Requires-Dist: sqlalchemy>=2.0.0
|
|
9
|
-
Requires-Dist: fastpluggy-ui-tools>=0.0.4
|
|
10
10
|
|
|
11
11
|
# Postgres Tools for FastPluggy
|
|
12
12
|
|
|
@@ -18,8 +18,6 @@ This plugin provides a user-friendly interface to monitor and manage various asp
|
|
|
18
18
|
|
|
19
19
|
## Features
|
|
20
20
|
|
|
21
|
-
### Implemented Features
|
|
22
|
-
|
|
23
21
|
- **PostgreSQL Sequences Monitoring**:
|
|
24
22
|
- View comprehensive sequence information including name, last value, max value, and remaining capacity
|
|
25
23
|
- Monitor sequence usage with percentage metrics (percent used and percent remaining)
|
|
@@ -94,7 +92,6 @@ This plugin provides a user-friendly interface to monitor and manage various asp
|
|
|
94
92
|
- Database configuration recommendations
|
|
95
93
|
- Key metrics summary
|
|
96
94
|
|
|
97
|
-
### Planned Features
|
|
98
95
|
|
|
99
96
|
For detailed specifications of each feature, see the individual files in the `docs/feature/` directory.
|
|
100
97
|
|
|
@@ -4,13 +4,13 @@ build-backend = "setuptools.build_meta"
|
|
|
4
4
|
|
|
5
5
|
[project]
|
|
6
6
|
name = "fastpluggy-postgres-tools"
|
|
7
|
-
version = "0.1.
|
|
7
|
+
version = "0.1.37"
|
|
8
8
|
readme = "README.md"
|
|
9
9
|
description = "PostgreSQL database monitoring and management plugin for FastPluggy"
|
|
10
10
|
requires-python = ">=3.10"
|
|
11
11
|
dependencies = [
|
|
12
|
+
"FastPluggy>=0.4.9",
|
|
12
13
|
"sqlalchemy>=2.0.0",
|
|
13
|
-
"fastpluggy-ui-tools>=0.0.4",
|
|
14
14
|
]
|
|
15
15
|
license = "MIT"
|
|
16
16
|
|
|
@@ -7,7 +7,12 @@ from fastpluggy.core.tools.inspect_tools import InjectDependency
|
|
|
7
7
|
from fastpluggy.fastpluggy import FastPluggy
|
|
8
8
|
|
|
9
9
|
|
|
10
|
-
def get_router():
|
|
10
|
+
def get_router() -> Any:
|
|
11
|
+
"""
|
|
12
|
+
Returns the router for PostgreSQL tools.
|
|
13
|
+
|
|
14
|
+
:return: The router object for PostgreSQL tools.
|
|
15
|
+
"""
|
|
11
16
|
from .routers import postgres_tools_router
|
|
12
17
|
return postgres_tools_router
|
|
13
18
|
|
|
@@ -18,11 +23,16 @@ class PostgresToolsModule(FastPluggyBaseModule):
|
|
|
18
23
|
module_menu_name: str = "Postgres"
|
|
19
24
|
module_menu_icon: str = "fas fa-database"
|
|
20
25
|
|
|
21
|
-
depends_on: dict = {
|
|
22
|
-
"ui_tools": ">=0.0.4",
|
|
23
|
-
}
|
|
26
|
+
depends_on: dict = {}
|
|
24
27
|
module_router: Any = get_router
|
|
25
28
|
|
|
26
29
|
def on_load_complete(self, fast_pluggy: Annotated[FastPluggy, InjectDependency]) -> None:
|
|
27
|
-
|
|
28
|
-
|
|
30
|
+
"""
|
|
31
|
+
Callback method called when the module is fully loaded.
|
|
32
|
+
|
|
33
|
+
Args:
|
|
34
|
+
fast_pluggy (Annotated[FastPluggy, InjectDependency]): The FastPluggy instance.
|
|
35
|
+
|
|
36
|
+
Note:
|
|
37
|
+
Menu items are now added using the @menu_entry decorator in the router files.
|
|
38
|
+
"""
|
|
@@ -1,16 +1,12 @@
|
|
|
1
1
|
from fastapi import APIRouter, Depends, Request, Form, HTTPException
|
|
2
|
-
from
|
|
3
|
-
from sqlalchemy import text, Table, Column, Integer, String, Float, Boolean, MetaData, create_engine
|
|
2
|
+
from sqlalchemy import text
|
|
4
3
|
from sqlalchemy.orm import Session
|
|
5
|
-
import json
|
|
6
4
|
import httpx
|
|
7
|
-
import
|
|
8
|
-
from typing import List, Dict, Any, Optional
|
|
5
|
+
from typing import Dict, Any, Optional
|
|
9
6
|
|
|
10
7
|
from fastpluggy.core.database import get_db
|
|
11
8
|
from fastpluggy.core.dependency import get_view_builder
|
|
12
|
-
from fastpluggy.core.widgets import
|
|
13
|
-
from fastpluggy.core.menu.decorator import menu_entry
|
|
9
|
+
from fastpluggy.core.widgets import CardWidget, FormWidget, TableWidget
|
|
14
10
|
|
|
15
11
|
alerts_router = APIRouter(prefix="/alerts", tags=["postgres_alerts"])
|
|
16
12
|
|
|
@@ -215,16 +211,11 @@ async def test_webhook(webhook_url: str, webhook_service: str, message: str):
|
|
|
215
211
|
timeout=10.0
|
|
216
212
|
)
|
|
217
213
|
return response.status_code < 400
|
|
218
|
-
except Exception
|
|
214
|
+
except Exception:
|
|
219
215
|
return False
|
|
220
216
|
|
|
221
217
|
|
|
222
218
|
@alerts_router.get("")
|
|
223
|
-
@menu_entry(
|
|
224
|
-
label="Alerts & Webhooks",
|
|
225
|
-
icon="fa fa-bell",
|
|
226
|
-
parent="postgres_tools"
|
|
227
|
-
)
|
|
228
219
|
async def get_alerts_view(
|
|
229
220
|
request: Request,
|
|
230
221
|
db=Depends(get_db),
|
{fastpluggy_postgres_tools-0.1.26 → fastpluggy_postgres_tools-0.1.37}/src/routers/connections.py
RENAMED
|
@@ -5,42 +5,60 @@ from sqlalchemy.orm import Session
|
|
|
5
5
|
from fastpluggy.core.database import get_db
|
|
6
6
|
from fastpluggy.core.dependency import get_view_builder
|
|
7
7
|
from fastpluggy.core.widgets import TableWidget
|
|
8
|
-
from fastpluggy.core.menu.decorator import menu_entry
|
|
9
8
|
|
|
10
9
|
connections_router = APIRouter(prefix="/connections", tags=["postgres_connections"])
|
|
11
10
|
|
|
11
|
+
# Valid values for pg_stat_activity.state — used to whitelist the ?state= filter
|
|
12
|
+
_VALID_ACTIVITY_STATES = frozenset({
|
|
13
|
+
"active",
|
|
14
|
+
"idle",
|
|
15
|
+
"idle in transaction",
|
|
16
|
+
"idle in transaction (aborted)",
|
|
17
|
+
"fastpath function call",
|
|
18
|
+
"disabled",
|
|
19
|
+
})
|
|
12
20
|
|
|
13
|
-
|
|
21
|
+
|
|
22
|
+
def get_active_connections(db: Session, min_duration: float = None, state: str = None):
|
|
14
23
|
"""
|
|
15
|
-
Get active connections from the database
|
|
24
|
+
Get active connections from the database.
|
|
25
|
+
|
|
26
|
+
Both *min_duration* and *state* are passed as bound parameters (never
|
|
27
|
+
interpolated into the SQL string) to prevent SQL injection. The *state*
|
|
28
|
+
value is also validated against the known set of pg_stat_activity states.
|
|
16
29
|
"""
|
|
17
30
|
where_conditions = ["state <> 'idle'"]
|
|
31
|
+
params = {}
|
|
18
32
|
|
|
19
|
-
if min_duration:
|
|
20
|
-
where_conditions.append(
|
|
33
|
+
if min_duration is not None:
|
|
34
|
+
where_conditions.append("EXTRACT(EPOCH FROM (now() - query_start)) > :min_duration")
|
|
35
|
+
params["min_duration"] = min_duration
|
|
21
36
|
|
|
22
37
|
if state:
|
|
23
|
-
|
|
38
|
+
# Whitelist: only accept well-known pg_stat_activity state values
|
|
39
|
+
if state in _VALID_ACTIVITY_STATES:
|
|
40
|
+
where_conditions.append("state = :state")
|
|
41
|
+
params["state"] = state
|
|
42
|
+
# Unknown values are silently ignored (no error, no injection)
|
|
24
43
|
|
|
25
44
|
where_clause = " AND ".join(where_conditions)
|
|
26
45
|
|
|
27
|
-
query = f"""
|
|
28
|
-
SELECT
|
|
46
|
+
query = text(f"""
|
|
47
|
+
SELECT
|
|
29
48
|
pid,
|
|
30
|
-
datname,
|
|
31
|
-
usename,
|
|
32
|
-
state,
|
|
33
|
-
backend_start,
|
|
49
|
+
datname,
|
|
50
|
+
usename,
|
|
51
|
+
state,
|
|
52
|
+
backend_start,
|
|
34
53
|
query_start,
|
|
35
54
|
EXTRACT(EPOCH FROM (now() - query_start)) AS duration_seconds,
|
|
36
55
|
query
|
|
37
56
|
FROM pg_stat_activity
|
|
38
57
|
WHERE {where_clause}
|
|
39
58
|
ORDER BY duration_seconds DESC
|
|
40
|
-
"""
|
|
59
|
+
""")
|
|
41
60
|
|
|
42
|
-
result = db.execute(
|
|
43
|
-
# Convert SQLAlchemy Result to list of dicts for TableWidget compatibility
|
|
61
|
+
result = db.execute(query, params)
|
|
44
62
|
return [dict(row) for row in result.mappings().all()]
|
|
45
63
|
|
|
46
64
|
|
|
@@ -72,11 +90,6 @@ def get_lock_contention(db_manager: Session):
|
|
|
72
90
|
|
|
73
91
|
|
|
74
92
|
@connections_router.get("")
|
|
75
|
-
@menu_entry(
|
|
76
|
-
label="Connections & Locks",
|
|
77
|
-
icon="fa fa-link",
|
|
78
|
-
parent="postgres_tools"
|
|
79
|
-
)
|
|
80
93
|
async def get_connections_view(
|
|
81
94
|
request: Request,
|
|
82
95
|
db=Depends(get_db),
|
{fastpluggy_postgres_tools-0.1.26 → fastpluggy_postgres_tools-0.1.37}/src/routers/dashboard.py
RENAMED
|
@@ -1,15 +1,14 @@
|
|
|
1
1
|
from fastapi import APIRouter, Depends, Request
|
|
2
2
|
from sqlalchemy import text
|
|
3
3
|
from sqlalchemy.orm import Session
|
|
4
|
-
from typing import List, Dict, Any
|
|
5
4
|
|
|
6
5
|
from fastpluggy.core.database import get_db
|
|
7
6
|
from fastpluggy.core.dependency import get_view_builder
|
|
8
|
-
from fastpluggy.core.widgets import TableWidget
|
|
9
|
-
from
|
|
10
|
-
from
|
|
7
|
+
from fastpluggy.core.widgets import CardWidget, TableWidget
|
|
8
|
+
from fastpluggy.core.widgets.categories.display.custom import CustomTemplateWidget
|
|
9
|
+
from ..utils import probe_pg_stat_statements, get_pg_version
|
|
11
10
|
|
|
12
|
-
dashboard_router = APIRouter(
|
|
11
|
+
dashboard_router = APIRouter()
|
|
13
12
|
|
|
14
13
|
|
|
15
14
|
def get_cluster_health(db: Session):
|
|
@@ -131,6 +130,11 @@ def get_recommendations(db: Session):
|
|
|
131
130
|
FROM pg_extension
|
|
132
131
|
WHERE extname = 'pg_stat_statements'
|
|
133
132
|
""")
|
|
133
|
+
|
|
134
|
+
# Check shared_preload_libraries for pg_stat_statements
|
|
135
|
+
shared_preload_check = text("""
|
|
136
|
+
SELECT current_setting('shared_preload_libraries', true) AS shared_preload_libraries
|
|
137
|
+
""")
|
|
134
138
|
|
|
135
139
|
# Check autovacuum settings
|
|
136
140
|
autovacuum_query = text("""
|
|
@@ -159,12 +163,23 @@ def get_recommendations(db: Session):
|
|
|
159
163
|
|
|
160
164
|
# Check pg_stat_statements extension
|
|
161
165
|
pg_stat_statements_result = db.execute(pg_stat_statements_query).mappings().first()
|
|
162
|
-
if pg_stat_statements_result
|
|
163
|
-
|
|
164
|
-
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
|
|
166
|
+
if pg_stat_statements_result:
|
|
167
|
+
if pg_stat_statements_result["count"] == 0:
|
|
168
|
+
recommendations.append({
|
|
169
|
+
"type": "extension",
|
|
170
|
+
"message": "Enable pg_stat_statements for query analysis",
|
|
171
|
+
"action": "CREATE EXTENSION pg_stat_statements;"
|
|
172
|
+
})
|
|
173
|
+
else:
|
|
174
|
+
# Extension installed; check if preloaded
|
|
175
|
+
preload_row = db.execute(shared_preload_check).mappings().first()
|
|
176
|
+
preload_val = (preload_row or {}).get("shared_preload_libraries") or ""
|
|
177
|
+
if "pg_stat_statements" not in preload_val:
|
|
178
|
+
recommendations.append({
|
|
179
|
+
"type": "extension",
|
|
180
|
+
"message": "pg_stat_statements installed but not loaded at startup",
|
|
181
|
+
"action": "Set shared_preload_libraries to include pg_stat_statements and restart PostgreSQL; then ensure CREATE EXTENSION pg_stat_statements; is run in each database as needed."
|
|
182
|
+
})
|
|
168
183
|
|
|
169
184
|
# Check autovacuum settings
|
|
170
185
|
autovacuum_result = db.execute(autovacuum_query).mappings().first()
|
|
@@ -198,82 +213,103 @@ def get_recommendations(db: Session):
|
|
|
198
213
|
|
|
199
214
|
def get_metrics_summary(db: Session):
|
|
200
215
|
"""
|
|
201
|
-
Get summary metrics for the dashboard
|
|
216
|
+
Get summary metrics for the dashboard.
|
|
217
|
+
|
|
218
|
+
Each metric is isolated so a single failure does not block the others.
|
|
219
|
+
pg_stat_statements is detected via a live probe query, making the check
|
|
220
|
+
reliable regardless of shared_preload_libraries string format or
|
|
221
|
+
information_schema column visibility. The timing column is selected
|
|
222
|
+
based on the server version (total_exec_time >= PG 13, total_time < PG 13).
|
|
202
223
|
"""
|
|
203
224
|
metrics = {}
|
|
204
|
-
|
|
205
|
-
#
|
|
225
|
+
|
|
226
|
+
# --- Bloat ---
|
|
206
227
|
bloat_query = text("""
|
|
207
228
|
SELECT AVG(ROUND(100.0 * n_dead_tup / GREATEST(n_live_tup + n_dead_tup, 1), 2)) AS avg_bloat
|
|
208
229
|
FROM pg_stat_user_tables
|
|
209
230
|
WHERE n_live_tup + n_dead_tup > 0
|
|
210
231
|
""")
|
|
211
|
-
|
|
212
|
-
|
|
213
|
-
|
|
214
|
-
|
|
215
|
-
|
|
216
|
-
)
|
|
217
|
-
|
|
218
|
-
|
|
219
|
-
#
|
|
220
|
-
#
|
|
221
|
-
|
|
222
|
-
|
|
223
|
-
|
|
224
|
-
|
|
225
|
-
|
|
226
|
-
|
|
227
|
-
|
|
228
|
-
|
|
229
|
-
|
|
230
|
-
|
|
232
|
+
try:
|
|
233
|
+
bloat_result = db.execute(bloat_query).mappings().first()
|
|
234
|
+
if bloat_result:
|
|
235
|
+
metrics["bloat_avg"] = round(bloat_result["avg_bloat"] or 0, 2)
|
|
236
|
+
except Exception as e:
|
|
237
|
+
metrics.setdefault("errors", []).append(f"bloat: {e}")
|
|
238
|
+
|
|
239
|
+
# --- Query latency via pg_stat_statements ---
|
|
240
|
+
# probe_pg_stat_statements() does two things:
|
|
241
|
+
# 1. checks whether the extension is registered in pg_extension
|
|
242
|
+
# 2. actually executes "SELECT 1 FROM pg_stat_statements LIMIT 0"
|
|
243
|
+
# This is the only reliable way to detect the "installed but not loaded"
|
|
244
|
+
# state, because information_schema.columns lists the view columns even
|
|
245
|
+
# when the module is absent from shared_preload_libraries.
|
|
246
|
+
try:
|
|
247
|
+
accessible, reason = probe_pg_stat_statements(db)
|
|
248
|
+
if not accessible:
|
|
249
|
+
metrics["query_latency_avg"] = "N/A"
|
|
250
|
+
metrics.setdefault("warnings", []).append(reason)
|
|
251
|
+
if "shared_preload_libraries" in (reason or ""):
|
|
252
|
+
metrics.setdefault("recommendations", []).append(
|
|
253
|
+
"Add 'pg_stat_statements' to shared_preload_libraries in "
|
|
254
|
+
"postgresql.conf and restart PostgreSQL. Then run "
|
|
255
|
+
"CREATE EXTENSION pg_stat_statements; in each database."
|
|
256
|
+
)
|
|
257
|
+
else:
|
|
258
|
+
# Select the correct timing column for this PG version.
|
|
259
|
+
# total_exec_time was introduced in PG 13 (server_version_num >= 130000).
|
|
260
|
+
# Older releases expose the same data as total_time.
|
|
261
|
+
pg_ver = get_pg_version(db)
|
|
262
|
+
time_col = "total_exec_time" if pg_ver >= 130000 else "total_time"
|
|
263
|
+
|
|
264
|
+
latency_sql = text(f"""
|
|
265
|
+
SELECT ROUND(AVG({time_col} / GREATEST(calls, 1)), 2) AS avg_latency
|
|
266
|
+
FROM pg_stat_statements
|
|
267
|
+
WHERE calls > 0
|
|
268
|
+
""")
|
|
269
|
+
try:
|
|
270
|
+
latency_result = db.execute(latency_sql).mappings().first()
|
|
271
|
+
metrics["query_latency_avg"] = (
|
|
272
|
+
round(latency_result["avg_latency"] or 0, 2) if latency_result else 0
|
|
273
|
+
)
|
|
274
|
+
except Exception as e:
|
|
275
|
+
try:
|
|
276
|
+
db.rollback()
|
|
277
|
+
except Exception:
|
|
278
|
+
pass
|
|
279
|
+
# Fallback string/pgcode check in case the probe raced a reload
|
|
280
|
+
from ..utils import is_pg_stat_prerequisite_error
|
|
281
|
+
if is_pg_stat_prerequisite_error(e):
|
|
282
|
+
metrics["query_latency_avg"] = "N/A"
|
|
283
|
+
metrics.setdefault("warnings", []).append(
|
|
284
|
+
"pg_stat_statements is not properly loaded. "
|
|
285
|
+
"Add it to shared_preload_libraries and restart PostgreSQL."
|
|
286
|
+
)
|
|
287
|
+
else:
|
|
288
|
+
metrics.setdefault("errors", []).append(f"latency: {e}")
|
|
289
|
+
except Exception as e:
|
|
290
|
+
metrics.setdefault("errors", []).append(f"latency_check: {e}")
|
|
291
|
+
|
|
292
|
+
# --- Autovacuum activity (last 24 h) ---
|
|
231
293
|
vacuum_query = text("""
|
|
232
294
|
SELECT COUNT(*) AS table_count
|
|
233
295
|
FROM pg_stat_user_tables
|
|
234
296
|
WHERE last_autovacuum > NOW() - INTERVAL '24 hours'
|
|
235
297
|
""")
|
|
236
|
-
|
|
237
298
|
try:
|
|
238
|
-
|
|
239
|
-
|
|
240
|
-
|
|
241
|
-
if bloat_result:
|
|
242
|
-
metrics["bloat_avg"] = round(bloat_result["avg_bloat"] or 0, 2)
|
|
243
|
-
|
|
244
|
-
# Check if pg_stat_statements is available
|
|
245
|
-
latency_check = db.execute(latency_query).mappings().first()
|
|
246
|
-
if latency_check and latency_check["has_pg_stat_statements"]:
|
|
247
|
-
# Get average query latency (try new schema first)
|
|
248
|
-
try:
|
|
249
|
-
latency_result = db.execute(latency_data_query_new).mappings().first()
|
|
250
|
-
except Exception:
|
|
251
|
-
# Rollback aborted transaction before retrying with legacy columns
|
|
252
|
-
try:
|
|
253
|
-
db.rollback()
|
|
254
|
-
except Exception:
|
|
255
|
-
pass
|
|
256
|
-
latency_result = db.execute(latency_data_query_legacy).mappings().first()
|
|
257
|
-
if latency_result:
|
|
258
|
-
metrics["query_latency_avg"] = round(latency_result["avg_latency"] or 0, 2)
|
|
259
|
-
|
|
260
|
-
# Get autovacuum runs per day
|
|
261
|
-
vacuum_result = db.execute(vacuum_query).mappings().first()
|
|
262
|
-
if vacuum_result:
|
|
263
|
-
metrics["vacuum_runs_24h"] = vacuum_result["table_count"]
|
|
299
|
+
vacuum_result = db.execute(vacuum_query).mappings().first()
|
|
300
|
+
if vacuum_result:
|
|
301
|
+
metrics["vacuum_runs_24h"] = vacuum_result["table_count"]
|
|
264
302
|
except Exception as e:
|
|
265
|
-
metrics
|
|
266
|
-
|
|
303
|
+
metrics.setdefault("errors", []).append(f"vacuum: {e}")
|
|
304
|
+
|
|
305
|
+
# Aggregate errors into a single human-readable string for the card
|
|
306
|
+
if metrics.get("errors"):
|
|
307
|
+
metrics["error"] = "; ".join(metrics["errors"])
|
|
308
|
+
|
|
267
309
|
return metrics
|
|
268
310
|
|
|
269
311
|
|
|
270
|
-
@dashboard_router.get("")
|
|
271
|
-
@menu_entry(
|
|
272
|
-
label="Dashboard",
|
|
273
|
-
icon="fa fa-tachometer-alt",
|
|
274
|
-
parent="postgres_tools",
|
|
275
|
-
position=0
|
|
276
|
-
)
|
|
312
|
+
@dashboard_router.get("/")
|
|
277
313
|
async def get_dashboard_view(
|
|
278
314
|
request: Request,
|
|
279
315
|
db=Depends(get_db),
|
|
@@ -327,6 +363,80 @@ async def get_dashboard_view(
|
|
|
327
363
|
content=metrics_content
|
|
328
364
|
)
|
|
329
365
|
widgets.append(metrics_card)
|
|
366
|
+
|
|
367
|
+
# Add a cool clickable cards grid for all Postgres Tools features
|
|
368
|
+
cards = [
|
|
369
|
+
{
|
|
370
|
+
"title": "Database Size",
|
|
371
|
+
"icon": "fas fa-database",
|
|
372
|
+
"description": "Explore overall DB size, schemas, tablespaces and largest tables.",
|
|
373
|
+
"url": request.url_for("get_db_size_view")
|
|
374
|
+
},
|
|
375
|
+
{
|
|
376
|
+
"title": "Sequences",
|
|
377
|
+
"icon": "fas fa-list-ol",
|
|
378
|
+
"description": "Check sequence usage and remaining capacity.",
|
|
379
|
+
"url": request.url_for("get_sequences_view")
|
|
380
|
+
},
|
|
381
|
+
{
|
|
382
|
+
"title": "Indexes",
|
|
383
|
+
"icon": "fas fa-layer-group",
|
|
384
|
+
"description": "Find large or unused indexes and scan counts.",
|
|
385
|
+
"url": request.url_for("get_indexes_view")
|
|
386
|
+
},
|
|
387
|
+
{
|
|
388
|
+
"title": "Tables",
|
|
389
|
+
"icon": "fas fa-table",
|
|
390
|
+
"description": "Detect table bloat, last vacuum/analyze and sizes.",
|
|
391
|
+
"url": request.url_for("get_tables_view")
|
|
392
|
+
},
|
|
393
|
+
{
|
|
394
|
+
"title": "Queries",
|
|
395
|
+
"icon": "fas fa-tachometer-alt",
|
|
396
|
+
"description": "Analyze heavy queries with pg_stat_statements.",
|
|
397
|
+
"url": request.url_for("get_queries_view")
|
|
398
|
+
},
|
|
399
|
+
{
|
|
400
|
+
"title": "Connections & Locks",
|
|
401
|
+
"icon": "fas fa-link",
|
|
402
|
+
"description": "Inspect active connections and lock contention.",
|
|
403
|
+
"url": request.url_for("get_connections_view")
|
|
404
|
+
},
|
|
405
|
+
{
|
|
406
|
+
"title": "Vacuum Status",
|
|
407
|
+
"icon": "fas fa-broom",
|
|
408
|
+
"description": "Track vacuum activity and autovacuum settings.",
|
|
409
|
+
"url": request.url_for("get_vacuum_view")
|
|
410
|
+
},
|
|
411
|
+
{
|
|
412
|
+
"title": "Replication & Backups",
|
|
413
|
+
"icon": "fas fa-sync",
|
|
414
|
+
"description": "Monitor replicas, slots and backup history.",
|
|
415
|
+
"url": request.url_for("get_replication_view")
|
|
416
|
+
},
|
|
417
|
+
{
|
|
418
|
+
"title": "Alerts & Webhooks",
|
|
419
|
+
"icon": "fas fa-bell",
|
|
420
|
+
"description": "Configure alert rules and send notifications.",
|
|
421
|
+
"url": request.url_for("get_alerts_view")
|
|
422
|
+
},
|
|
423
|
+
{
|
|
424
|
+
"title": "Extensions",
|
|
425
|
+
"icon": "fas fa-plug",
|
|
426
|
+
"description": "List and manage available PostgreSQL extensions.",
|
|
427
|
+
"url": request.url_for("get_extensions_view")
|
|
428
|
+
},
|
|
429
|
+
]
|
|
430
|
+
|
|
431
|
+
widgets.append(
|
|
432
|
+
CustomTemplateWidget(
|
|
433
|
+
template_name="postgres_tools/dashboard_cards.html.j2",
|
|
434
|
+
context={
|
|
435
|
+
"title": "PostgreSQL Tools",
|
|
436
|
+
"cards": cards
|
|
437
|
+
}
|
|
438
|
+
)
|
|
439
|
+
)
|
|
330
440
|
|
|
331
441
|
# Render the view
|
|
332
442
|
return view_builder.generate(
|
{fastpluggy_postgres_tools-0.1.26 → fastpluggy_postgres_tools-0.1.37}/src/routers/db_size.py
RENAMED
|
@@ -1,12 +1,11 @@
|
|
|
1
|
-
from fastapi import APIRouter, Depends, Request
|
|
1
|
+
from fastapi import APIRouter, Depends, HTTPException, Request
|
|
2
2
|
from sqlalchemy import text
|
|
3
3
|
from sqlalchemy.orm import Session
|
|
4
4
|
|
|
5
5
|
from fastpluggy.core.database import get_db
|
|
6
6
|
from fastpluggy.core.dependency import get_view_builder
|
|
7
|
-
from fastpluggy.core.widgets import TableWidget
|
|
8
|
-
from
|
|
9
|
-
from fastpluggy.core.menu.decorator import menu_entry
|
|
7
|
+
from fastpluggy.core.widgets import CardWidget, TableWidget
|
|
8
|
+
from ..utils import validate_pg_identifier
|
|
10
9
|
|
|
11
10
|
db_size_router = APIRouter(prefix="/db/size", tags=["postgres_db_size"])
|
|
12
11
|
|
|
@@ -60,6 +59,9 @@ def get_tablespace_sizes(db: Session):
|
|
|
60
59
|
|
|
61
60
|
|
|
62
61
|
def get_largest_tables(db: Session, limit: int = 20, schema: str = None):
|
|
62
|
+
if schema and not validate_pg_identifier(schema):
|
|
63
|
+
raise HTTPException(status_code=400, detail="Invalid schema name")
|
|
64
|
+
|
|
63
65
|
where_clause = ""
|
|
64
66
|
if schema:
|
|
65
67
|
where_clause = f"WHERE schemaname = '{schema}'"
|
|
@@ -83,11 +85,6 @@ def get_largest_tables(db: Session, limit: int = 20, schema: str = None):
|
|
|
83
85
|
|
|
84
86
|
|
|
85
87
|
@db_size_router.get("")
|
|
86
|
-
@menu_entry(
|
|
87
|
-
label="Database Size",
|
|
88
|
-
icon="fa fa-database",
|
|
89
|
-
parent="postgres_tools"
|
|
90
|
-
)
|
|
91
88
|
async def get_db_size_view(
|
|
92
89
|
request: Request,
|
|
93
90
|
db=Depends(get_db),
|
{fastpluggy_postgres_tools-0.1.26 → fastpluggy_postgres_tools-0.1.37}/src/routers/extensions.py
RENAMED
|
@@ -5,7 +5,6 @@ from sqlalchemy.orm import Session
|
|
|
5
5
|
from fastpluggy.core.database import get_db
|
|
6
6
|
from fastpluggy.core.dependency import get_view_builder
|
|
7
7
|
from fastpluggy.core.widgets import TableWidget
|
|
8
|
-
from fastpluggy.core.menu.decorator import menu_entry
|
|
9
8
|
|
|
10
9
|
extensions_router = APIRouter(prefix="/extensions", tags=["postgres_extensions"])
|
|
11
10
|
|
|
@@ -32,11 +31,6 @@ def get_available_extensions(db: Session):
|
|
|
32
31
|
|
|
33
32
|
|
|
34
33
|
@extensions_router.get("")
|
|
35
|
-
@menu_entry(
|
|
36
|
-
label="Extensions",
|
|
37
|
-
icon="fa fa-plug",
|
|
38
|
-
parent="postgres_tools"
|
|
39
|
-
)
|
|
40
34
|
async def get_extensions_view(
|
|
41
35
|
request: Request,
|
|
42
36
|
db=Depends(get_db),
|
{fastpluggy_postgres_tools-0.1.26 → fastpluggy_postgres_tools-0.1.37}/src/routers/indexes.py
RENAMED
|
@@ -1,19 +1,24 @@
|
|
|
1
|
-
from fastapi import APIRouter, Depends, Request
|
|
1
|
+
from fastapi import APIRouter, Depends, HTTPException, Request
|
|
2
2
|
from sqlalchemy import text
|
|
3
3
|
from sqlalchemy.orm import Session
|
|
4
4
|
|
|
5
5
|
from fastpluggy.core.database import get_db
|
|
6
6
|
from fastpluggy.core.dependency import get_view_builder
|
|
7
7
|
from fastpluggy.core.widgets import TableWidget
|
|
8
|
-
from
|
|
8
|
+
from ..utils import validate_pg_identifier
|
|
9
9
|
|
|
10
10
|
indexes_router = APIRouter(prefix="/indexes", tags=["postgres_indexes"])
|
|
11
11
|
|
|
12
12
|
|
|
13
13
|
def get_index_usage_statistics(db: Session, schema: str = None, threshold_unused: int = 10):
|
|
14
14
|
"""
|
|
15
|
-
Get index usage statistics from the database
|
|
15
|
+
Get index usage statistics from the database.
|
|
16
|
+
|
|
17
|
+
*schema* is validated before use to prevent SQL injection.
|
|
16
18
|
"""
|
|
19
|
+
if schema and not validate_pg_identifier(schema):
|
|
20
|
+
raise HTTPException(status_code=400, detail="Invalid schema name")
|
|
21
|
+
|
|
17
22
|
where_clause = "WHERE s.schemaname NOT IN ('pg_catalog', 'information_schema')"
|
|
18
23
|
if schema:
|
|
19
24
|
where_clause += f" AND s.schemaname = '{schema}'"
|
|
@@ -39,11 +44,6 @@ def get_index_usage_statistics(db: Session, schema: str = None, threshold_unused
|
|
|
39
44
|
|
|
40
45
|
|
|
41
46
|
@indexes_router.get("")
|
|
42
|
-
@menu_entry(
|
|
43
|
-
label="Index Usage",
|
|
44
|
-
icon="fa fa-table",
|
|
45
|
-
parent="postgres_tools"
|
|
46
|
-
)
|
|
47
47
|
async def get_indexes_view(
|
|
48
48
|
request: Request,
|
|
49
49
|
db=Depends(get_db),
|
{fastpluggy_postgres_tools-0.1.26 → fastpluggy_postgres_tools-0.1.37}/src/routers/queries.py
RENAMED
|
@@ -1,75 +1,63 @@
|
|
|
1
1
|
from fastapi import APIRouter, Depends, Request
|
|
2
2
|
from fastapi.responses import RedirectResponse
|
|
3
|
-
from fastpluggy_plugin.ui_tools.extra_widget.display.card import CardWidget
|
|
4
3
|
from sqlalchemy.orm import Session
|
|
5
4
|
|
|
6
5
|
from fastpluggy.core.database import get_db
|
|
7
6
|
from fastpluggy.core.dependency import get_view_builder
|
|
8
|
-
from fastpluggy.core.
|
|
9
|
-
from
|
|
10
|
-
from ..utils import execute_query_first, execute_query
|
|
7
|
+
from fastpluggy.core.widgets import CardWidget, TableWidget
|
|
8
|
+
from ..utils import execute_query, probe_pg_stat_statements, get_pg_version
|
|
11
9
|
|
|
12
10
|
queries_router = APIRouter(prefix="/queries", tags=["postgres_queries"])
|
|
13
11
|
|
|
14
12
|
|
|
15
|
-
def check_pg_stat_statements(db_manager: Session):
|
|
16
|
-
"""
|
|
17
|
-
Check if pg_stat_statements extension is installed
|
|
18
|
-
"""
|
|
19
|
-
query = """
|
|
20
|
-
SELECT COUNT(*) AS count
|
|
21
|
-
FROM pg_extension
|
|
22
|
-
WHERE extname = 'pg_stat_statements'
|
|
23
|
-
"""
|
|
24
|
-
|
|
25
|
-
result = execute_query_first(db=db_manager,query_text=query)
|
|
26
|
-
print(
|
|
27
|
-
f"pg_stat_statements extension is {'installed' if result['count'] > 0 else 'not installed'}"
|
|
28
|
-
)
|
|
29
|
-
return result["count"] > 0
|
|
30
|
-
|
|
31
|
-
|
|
32
13
|
def get_query_performance_statistics(db_manager: Session, limit: int = 10, include_p95: bool = False):
|
|
33
14
|
"""
|
|
34
|
-
Get query performance statistics from
|
|
15
|
+
Get query performance statistics from pg_stat_statements.
|
|
16
|
+
|
|
17
|
+
Uses probe_pg_stat_statements() to verify the extension is both installed
|
|
18
|
+
*and* accessible (i.e. loaded via shared_preload_libraries), then selects
|
|
19
|
+
the correct timing column for the running PostgreSQL version:
|
|
20
|
+
- PG >= 13: total_exec_time
|
|
21
|
+
- PG < 13: total_time
|
|
22
|
+
Returns (rows, True) on success or ([], False) when the extension is absent
|
|
23
|
+
or not loaded. A human-readable *reason* string is returned as the third
|
|
24
|
+
element so callers can display a helpful message.
|
|
35
25
|
"""
|
|
36
|
-
|
|
37
|
-
|
|
26
|
+
accessible, reason = probe_pg_stat_statements(db_manager)
|
|
27
|
+
if not accessible:
|
|
28
|
+
return [], False, reason
|
|
38
29
|
|
|
39
|
-
|
|
40
|
-
|
|
30
|
+
pg_ver = get_pg_version(db_manager)
|
|
31
|
+
time_col = "total_exec_time" if pg_ver >= 130000 else "total_time"
|
|
41
32
|
|
|
42
|
-
# Build a version-agnostic query using COALESCE to support PG13+ and PG15+ column names
|
|
43
|
-
# We compute mean/avg from total/calls to avoid relying on mean_* columns which vary by version
|
|
44
33
|
p95_column = ""
|
|
45
|
-
# Note: 95th percentile is based on derived per-call time for compatibility across versions
|
|
46
34
|
if include_p95:
|
|
47
|
-
p95_column =
|
|
35
|
+
p95_column = (
|
|
36
|
+
f", (SELECT percentile_cont(0.95) WITHIN GROUP "
|
|
37
|
+
f"(ORDER BY {time_col}/GREATEST(calls,1)) "
|
|
38
|
+
f"FROM pg_stat_statements) AS p95_time"
|
|
39
|
+
)
|
|
48
40
|
|
|
49
41
|
query = f"""
|
|
50
42
|
SELECT
|
|
51
43
|
query,
|
|
52
44
|
calls,
|
|
53
|
-
|
|
54
|
-
ROUND(
|
|
55
|
-
ROUND(
|
|
45
|
+
{time_col} AS total_time,
|
|
46
|
+
ROUND({time_col} / GREATEST(calls, 1), 2) AS mean_time,
|
|
47
|
+
ROUND({time_col} / GREATEST(calls, 1), 2) AS avg_time,
|
|
56
48
|
SUBSTRING(query, 1, 100) AS truncated_query
|
|
57
49
|
{p95_column}
|
|
58
50
|
FROM pg_stat_statements
|
|
59
|
-
|
|
51
|
+
WHERE calls > 0
|
|
52
|
+
ORDER BY {time_col} DESC
|
|
60
53
|
LIMIT :limit
|
|
61
54
|
"""
|
|
62
55
|
|
|
63
56
|
result = execute_query(db_manager, query, {"limit": limit})
|
|
64
|
-
return result, True
|
|
57
|
+
return result, True, None
|
|
65
58
|
|
|
66
59
|
|
|
67
60
|
@queries_router.get("")
|
|
68
|
-
@menu_entry(
|
|
69
|
-
label="Query Performance",
|
|
70
|
-
icon="fa fa-tachometer",
|
|
71
|
-
parent="postgres_tools"
|
|
72
|
-
)
|
|
73
61
|
async def get_queries_view(
|
|
74
62
|
request: Request,
|
|
75
63
|
db=Depends(get_db),
|
|
@@ -83,18 +71,29 @@ async def get_queries_view(
|
|
|
83
71
|
# Create a connection manager for this request
|
|
84
72
|
|
|
85
73
|
# Get query performance statistics
|
|
86
|
-
query_stats, has_extension = get_query_performance_statistics(db, limit, include_p95)
|
|
74
|
+
query_stats, has_extension, unavail_reason = get_query_performance_statistics(db, limit, include_p95)
|
|
87
75
|
|
|
88
76
|
if not has_extension:
|
|
89
|
-
|
|
77
|
+
content_lines = [
|
|
78
|
+
"<p>The <strong>pg_stat_statements</strong> extension is required for query performance analysis.</p>",
|
|
79
|
+
]
|
|
80
|
+
if unavail_reason and "not installed" in unavail_reason:
|
|
81
|
+
content_lines += [
|
|
82
|
+
"<p>To install it, run the following SQL command as a superuser:</p>",
|
|
83
|
+
"<pre>CREATE EXTENSION IF NOT EXISTS pg_stat_statements;</pre>",
|
|
84
|
+
"<p>Then add <code>pg_stat_statements</code> to "
|
|
85
|
+
"<code>shared_preload_libraries</code> in postgresql.conf and restart PostgreSQL.</p>",
|
|
86
|
+
]
|
|
87
|
+
elif unavail_reason:
|
|
88
|
+
content_lines += [
|
|
89
|
+
f"<p><strong>Reason:</strong> {unavail_reason}</p>",
|
|
90
|
+
"<p>To enable latency metrics, add <code>pg_stat_statements</code> to "
|
|
91
|
+
"<code>shared_preload_libraries</code> in postgresql.conf and restart PostgreSQL.</p>",
|
|
92
|
+
]
|
|
93
|
+
|
|
90
94
|
extension_card = CardWidget(
|
|
91
|
-
title="
|
|
92
|
-
content=""
|
|
93
|
-
<p>The pg_stat_statements extension is required for query performance analysis.</p>
|
|
94
|
-
<p>To install it, run the following SQL command:</p>
|
|
95
|
-
<pre>CREATE EXTENSION IF NOT EXISTS pg_stat_statements;</pre>
|
|
96
|
-
<p>You may need superuser privileges to install this extension.</p>
|
|
97
|
-
""",
|
|
95
|
+
title="pg_stat_statements Unavailable",
|
|
96
|
+
content="\n".join(content_lines),
|
|
98
97
|
links=[
|
|
99
98
|
{
|
|
100
99
|
"url": request.url_for("install_pg_stat_statements"),
|
{fastpluggy_postgres_tools-0.1.26 → fastpluggy_postgres_tools-0.1.37}/src/routers/replication.py
RENAMED
|
@@ -4,10 +4,8 @@ from sqlalchemy.orm import Session
|
|
|
4
4
|
|
|
5
5
|
from fastpluggy.core.database import get_db
|
|
6
6
|
from fastpluggy.core.dependency import get_view_builder
|
|
7
|
-
from fastpluggy.core.widgets import TableWidget
|
|
8
|
-
from fastpluggy_plugin.ui_tools.extra_widget.display.card import CardWidget
|
|
7
|
+
from fastpluggy.core.widgets import CardWidget, TableWidget
|
|
9
8
|
|
|
10
|
-
from fastpluggy.core.menu.decorator import menu_entry
|
|
11
9
|
|
|
12
10
|
replication_router = APIRouter(prefix="/replication", tags=["postgres_replication"])
|
|
13
11
|
|
|
@@ -40,7 +38,7 @@ def get_replication_status(db: Session):
|
|
|
40
38
|
|
|
41
39
|
result = db.execute(query).mappings()
|
|
42
40
|
return [dict(row) for row in result]
|
|
43
|
-
except Exception
|
|
41
|
+
except Exception:
|
|
44
42
|
# This might fail if not running on a primary server
|
|
45
43
|
return []
|
|
46
44
|
|
|
@@ -64,7 +62,7 @@ def get_replication_slots(db: Session):
|
|
|
64
62
|
|
|
65
63
|
result = db.execute(query).mappings()
|
|
66
64
|
return [dict(row) for row in result]
|
|
67
|
-
except Exception
|
|
65
|
+
except Exception:
|
|
68
66
|
# This might fail if not running on a primary server
|
|
69
67
|
return []
|
|
70
68
|
|
|
@@ -108,17 +106,12 @@ def get_backup_history(db: Session, limit: int = 10):
|
|
|
108
106
|
|
|
109
107
|
result = db.execute(query).mappings()
|
|
110
108
|
return [dict(row) for row in result]
|
|
111
|
-
except Exception
|
|
109
|
+
except Exception:
|
|
112
110
|
# This might fail if the table doesn't exist
|
|
113
111
|
return []
|
|
114
112
|
|
|
115
113
|
|
|
116
114
|
@replication_router.get("")
|
|
117
|
-
@menu_entry(
|
|
118
|
-
label="Replication & Backups",
|
|
119
|
-
icon="fa fa-sync",
|
|
120
|
-
parent="postgres_tools"
|
|
121
|
-
)
|
|
122
115
|
async def get_replication_view(
|
|
123
116
|
request: Request,
|
|
124
117
|
db=Depends(get_db),
|
{fastpluggy_postgres_tools-0.1.26 → fastpluggy_postgres_tools-0.1.37}/src/routers/sequences.py
RENAMED
|
@@ -5,7 +5,6 @@ from sqlalchemy.orm import Session
|
|
|
5
5
|
from fastpluggy.core.database import get_db
|
|
6
6
|
from fastpluggy.core.dependency import get_view_builder
|
|
7
7
|
from fastpluggy.core.widgets import TableWidget
|
|
8
|
-
from fastpluggy.core.menu.decorator import menu_entry
|
|
9
8
|
|
|
10
9
|
sequences_router = APIRouter(prefix="/sequences", tags=["postgres_sequences"])
|
|
11
10
|
|
|
@@ -50,11 +49,6 @@ def get_sequences_data(db: Session):
|
|
|
50
49
|
|
|
51
50
|
|
|
52
51
|
@sequences_router.get("")
|
|
53
|
-
@menu_entry(
|
|
54
|
-
label="Sequences",
|
|
55
|
-
icon="fa fa-list",
|
|
56
|
-
parent="postgres_tools"
|
|
57
|
-
)
|
|
58
52
|
async def get_sequences_view(request: Request, db=Depends(get_db), view_builder=Depends(get_view_builder)):
|
|
59
53
|
"""
|
|
60
54
|
Get the PostgreSQL sequences view
|
|
@@ -1,20 +1,24 @@
|
|
|
1
|
-
from fastapi import APIRouter, Depends, Request
|
|
1
|
+
from fastapi import APIRouter, Depends, HTTPException, Request
|
|
2
2
|
from sqlalchemy import text
|
|
3
3
|
from sqlalchemy.orm import Session
|
|
4
4
|
|
|
5
5
|
from fastpluggy.core.database import get_db
|
|
6
6
|
from fastpluggy.core.dependency import get_view_builder
|
|
7
7
|
from fastpluggy.core.widgets import TableWidget
|
|
8
|
-
from
|
|
9
|
-
from ..utils import execute_query_first
|
|
8
|
+
from ..utils import execute_query_first, validate_pg_identifier
|
|
10
9
|
|
|
11
10
|
tables_router = APIRouter(prefix="/tables", tags=["postgres_tables"])
|
|
12
11
|
|
|
13
12
|
|
|
14
13
|
def get_table_statistics(db_manager: Session, schema: str = None, threshold_warn: int = 20, threshold_error: int = 40):
|
|
15
14
|
"""
|
|
16
|
-
Get table statistics from the database including bloat estimation
|
|
15
|
+
Get table statistics from the database including bloat estimation.
|
|
16
|
+
|
|
17
|
+
*schema* is validated before use to prevent SQL injection.
|
|
17
18
|
"""
|
|
19
|
+
if schema and not validate_pg_identifier(schema):
|
|
20
|
+
raise HTTPException(status_code=400, detail="Invalid schema name")
|
|
21
|
+
|
|
18
22
|
where_clause = "WHERE schemaname NOT IN ('pg_catalog', 'information_schema')"
|
|
19
23
|
if schema:
|
|
20
24
|
where_clause += f" AND schemaname = '{schema}'"
|
|
@@ -42,7 +46,8 @@ def get_table_statistics(db_manager: Session, schema: str = None, threshold_warn
|
|
|
42
46
|
ORDER BY bloat_percent DESC
|
|
43
47
|
"""
|
|
44
48
|
|
|
45
|
-
|
|
49
|
+
result = db_manager.execute(text(query)).mappings()
|
|
50
|
+
return [dict(row) for row in result]
|
|
46
51
|
|
|
47
52
|
|
|
48
53
|
def check_pgstattuple_extension(db_manager: Session):
|
|
@@ -60,11 +65,6 @@ def check_pgstattuple_extension(db_manager: Session):
|
|
|
60
65
|
|
|
61
66
|
|
|
62
67
|
@tables_router.get("")
|
|
63
|
-
@menu_entry(
|
|
64
|
-
label="Table Statistics",
|
|
65
|
-
icon="fa fa-table",
|
|
66
|
-
parent="postgres_tools"
|
|
67
|
-
)
|
|
68
68
|
async def get_tables_view(
|
|
69
69
|
request: Request,
|
|
70
70
|
db=Depends(get_db),
|
|
@@ -10,10 +10,10 @@ from starlette.responses import RedirectResponse
|
|
|
10
10
|
from fastpluggy.core.database import get_db
|
|
11
11
|
from fastpluggy.core.dependency import get_view_builder
|
|
12
12
|
from fastpluggy.core.flash import FlashMessage
|
|
13
|
-
from fastpluggy.core.menu.decorator import menu_entry
|
|
14
13
|
from fastpluggy.core.widgets import TableWidget
|
|
15
14
|
from fastpluggy.core.widgets.categories.input.button import AutoLinkWidget
|
|
16
15
|
from fastpluggy.core.widgets.categories.input.button_list import ButtonListWidget
|
|
16
|
+
from ..utils import validate_pg_identifier
|
|
17
17
|
|
|
18
18
|
vacuum_router = APIRouter(prefix="/vacuum", tags=["postgres_vacuum"])
|
|
19
19
|
|
|
@@ -27,13 +27,20 @@ class VacuumRequest(BaseModel):
|
|
|
27
27
|
|
|
28
28
|
def get_table_vacuum_status(db: Session, schema: str = None, days_since_vacuum: int = None):
|
|
29
29
|
"""
|
|
30
|
-
Get vacuum status for tables
|
|
30
|
+
Get vacuum status for tables.
|
|
31
|
+
|
|
32
|
+
*schema* is validated as a safe identifier before being embedded in SQL.
|
|
33
|
+
*days_since_vacuum* is an int (type-checked by FastAPI) so it is safe to
|
|
34
|
+
embed directly, but it is compared server-side against a computed value.
|
|
31
35
|
"""
|
|
36
|
+
if schema and not validate_pg_identifier(schema):
|
|
37
|
+
raise HTTPException(status_code=400, detail="Invalid schema name")
|
|
38
|
+
|
|
32
39
|
where_clause = "WHERE schemaname NOT IN ('pg_catalog', 'information_schema')"
|
|
33
40
|
if schema:
|
|
34
41
|
where_clause += f" AND schemaname = '{schema}'"
|
|
35
42
|
if days_since_vacuum:
|
|
36
|
-
where_clause += f" AND EXTRACT(EPOCH FROM (now() - COALESCE(last_vacuum, last_autovacuum, '1970-01-01'::timestamp)))/86400 > {days_since_vacuum}"
|
|
43
|
+
where_clause += f" AND EXTRACT(EPOCH FROM (now() - COALESCE(last_vacuum, last_autovacuum, '1970-01-01'::timestamp)))/86400 > {int(days_since_vacuum)}"
|
|
37
44
|
|
|
38
45
|
query = text(f"""
|
|
39
46
|
SELECT
|
|
@@ -178,11 +185,6 @@ async def trigger_vacuum(
|
|
|
178
185
|
|
|
179
186
|
|
|
180
187
|
@vacuum_router.get("")
|
|
181
|
-
@menu_entry(
|
|
182
|
-
label="Vacuum Status",
|
|
183
|
-
icon="fa fa-broom",
|
|
184
|
-
parent="postgres_tools"
|
|
185
|
-
)
|
|
186
188
|
async def get_vacuum_view(
|
|
187
189
|
request: Request,
|
|
188
190
|
db=Depends(get_db),
|
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
{#
|
|
2
|
+
PostgreSQL Tools - Dashboard Cards Grid
|
|
3
|
+
Context (prefixed by widget):
|
|
4
|
+
- widget.title: string
|
|
5
|
+
- widget.cards: list of { title, icon, description, url }
|
|
6
|
+
#}
|
|
7
|
+
<div class="card mb-3">
|
|
8
|
+
<div class="card-body">
|
|
9
|
+
<h5 class="card-title mb-0">
|
|
10
|
+
<i class="fas fa-toolbox me-2"></i>{{ widget.title or 'PostgreSQL Tools' }}
|
|
11
|
+
</h5>
|
|
12
|
+
</div>
|
|
13
|
+
</div>
|
|
14
|
+
|
|
15
|
+
<div class="row g-3">
|
|
16
|
+
{% for c in widget.cards %}
|
|
17
|
+
<div class="col-12 col-sm-6 col-lg-4 col-xl-3">
|
|
18
|
+
<a href="{{ c.url }}" class="text-decoration-none text-reset">
|
|
19
|
+
<div class="card h-100 shadow-sm border-0 card-hover">
|
|
20
|
+
<div class="card-body d-flex flex-column">
|
|
21
|
+
<div class="d-flex align-items-center mb-2">
|
|
22
|
+
{% if c.icon %}
|
|
23
|
+
<i class="{{ c.icon }} text-primary me-2" style="font-size: 1.25rem;"></i>
|
|
24
|
+
{% else %}
|
|
25
|
+
<i class="fas fa-circle text-primary me-2" style="font-size: 1.25rem;"></i>
|
|
26
|
+
{% endif %}
|
|
27
|
+
<h6 class="card-title mb-0">{{ c.title }}</h6>
|
|
28
|
+
</div>
|
|
29
|
+
{% if c.description %}
|
|
30
|
+
<p class="card-text text-muted small flex-grow-1">{{ c.description }}</p>
|
|
31
|
+
{% endif %}
|
|
32
|
+
<div class="mt-2 d-flex align-items-center text-primary small fw-semibold">
|
|
33
|
+
<span>Open</span>
|
|
34
|
+
<i class="fas fa-arrow-right ms-2"></i>
|
|
35
|
+
</div>
|
|
36
|
+
</div>
|
|
37
|
+
</div>
|
|
38
|
+
</a>
|
|
39
|
+
</div>
|
|
40
|
+
{% endfor %}
|
|
41
|
+
</div>
|
|
42
|
+
|
|
43
|
+
<style>
|
|
44
|
+
.card-hover { transition: transform .12s ease, box-shadow .12s ease; }
|
|
45
|
+
.card-hover:hover { transform: translateY(-2px); box-shadow: 0 .5rem 1rem rgba(0,0,0,.08) !important; }
|
|
46
|
+
</style>
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Utility functions for postgres_tools.
|
|
3
|
+
"""
|
|
4
|
+
|
|
5
|
+
from .db_utils import (
|
|
6
|
+
execute_query,
|
|
7
|
+
execute_query_first,
|
|
8
|
+
execute_command,
|
|
9
|
+
validate_pg_identifier,
|
|
10
|
+
is_pg_stat_prerequisite_error,
|
|
11
|
+
probe_pg_stat_statements,
|
|
12
|
+
get_pg_version,
|
|
13
|
+
)
|
|
14
|
+
|
|
15
|
+
__all__ = [
|
|
16
|
+
"execute_query",
|
|
17
|
+
"execute_query_first",
|
|
18
|
+
"execute_command",
|
|
19
|
+
"validate_pg_identifier",
|
|
20
|
+
"is_pg_stat_prerequisite_error",
|
|
21
|
+
"probe_pg_stat_statements",
|
|
22
|
+
"get_pg_version",
|
|
23
|
+
]
|
|
@@ -2,10 +2,104 @@
|
|
|
2
2
|
Database utility functions for postgres_tools.
|
|
3
3
|
"""
|
|
4
4
|
|
|
5
|
+
import re
|
|
5
6
|
from sqlalchemy import text
|
|
6
7
|
from sqlalchemy.orm import Session
|
|
7
8
|
|
|
8
9
|
|
|
10
|
+
# ---------------------------------------------------------------------------
|
|
11
|
+
# PostgreSQL identifier validation
|
|
12
|
+
# ---------------------------------------------------------------------------
|
|
13
|
+
|
|
14
|
+
_PG_IDENTIFIER_RE = re.compile(r"^[a-zA-Z_][a-zA-Z0-9_$]*$")
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
def validate_pg_identifier(name: str) -> bool:
|
|
18
|
+
"""
|
|
19
|
+
Return True if *name* is a safe, unquoted PostgreSQL identifier.
|
|
20
|
+
Accepts letters, digits, underscores and dollar signs; max 63 chars.
|
|
21
|
+
"""
|
|
22
|
+
return bool(name and _PG_IDENTIFIER_RE.match(name) and len(name) <= 63)
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
# ---------------------------------------------------------------------------
|
|
26
|
+
# pg_stat_statements helpers (version-aware)
|
|
27
|
+
# ---------------------------------------------------------------------------
|
|
28
|
+
|
|
29
|
+
def is_pg_stat_prerequisite_error(exc) -> bool:
|
|
30
|
+
"""
|
|
31
|
+
Return True when *exc* signals that pg_stat_statements is not loaded via
|
|
32
|
+
shared_preload_libraries. Checks both the string representation and the
|
|
33
|
+
underlying driver pgcode (55000 = object_not_in_prerequisite_state).
|
|
34
|
+
Works with psycopg2, psycopg3, and any SQLAlchemy-wrapped variant.
|
|
35
|
+
"""
|
|
36
|
+
msg = str(exc)
|
|
37
|
+
if "ObjectNotInPrerequisiteState" in msg or "pg_stat_statements must be loaded via" in msg:
|
|
38
|
+
return True
|
|
39
|
+
for attr in ("orig", "__cause__"):
|
|
40
|
+
cause = getattr(exc, attr, None)
|
|
41
|
+
if cause and getattr(cause, "pgcode", None) == "55000":
|
|
42
|
+
return True
|
|
43
|
+
return False
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
def probe_pg_stat_statements(db: Session) -> tuple:
|
|
47
|
+
"""
|
|
48
|
+
Check whether pg_stat_statements is installed AND accessible.
|
|
49
|
+
|
|
50
|
+
Returns:
|
|
51
|
+
(accessible: bool, reason: str | None)
|
|
52
|
+
*reason* is None when accessible, or a human-friendly message when not.
|
|
53
|
+
"""
|
|
54
|
+
# Step 1: is the extension registered?
|
|
55
|
+
try:
|
|
56
|
+
row = db.execute(text(
|
|
57
|
+
"SELECT EXISTS("
|
|
58
|
+
" SELECT 1 FROM pg_extension WHERE extname='pg_stat_statements'"
|
|
59
|
+
") AS has_ext"
|
|
60
|
+
)).mappings().first()
|
|
61
|
+
if not row or not row["has_ext"]:
|
|
62
|
+
return False, (
|
|
63
|
+
"pg_stat_statements extension is not installed. "
|
|
64
|
+
"Run: CREATE EXTENSION pg_stat_statements; "
|
|
65
|
+
"and add 'pg_stat_statements' to shared_preload_libraries."
|
|
66
|
+
)
|
|
67
|
+
except Exception as e:
|
|
68
|
+
return False, f"Could not query pg_extension: {e}"
|
|
69
|
+
|
|
70
|
+
# Step 2: actually access the view (installed ≠ loaded)
|
|
71
|
+
try:
|
|
72
|
+
db.execute(text("SELECT 1 FROM pg_stat_statements LIMIT 0"))
|
|
73
|
+
return True, None
|
|
74
|
+
except Exception as e:
|
|
75
|
+
try:
|
|
76
|
+
db.rollback()
|
|
77
|
+
except Exception:
|
|
78
|
+
pass
|
|
79
|
+
if is_pg_stat_prerequisite_error(e):
|
|
80
|
+
return False, (
|
|
81
|
+
"pg_stat_statements is installed but not loaded via "
|
|
82
|
+
"shared_preload_libraries. Add 'pg_stat_statements' to "
|
|
83
|
+
"shared_preload_libraries in postgresql.conf and restart PostgreSQL."
|
|
84
|
+
)
|
|
85
|
+
return False, f"pg_stat_statements probe failed: {e}"
|
|
86
|
+
|
|
87
|
+
|
|
88
|
+
def get_pg_version(db: Session) -> int:
|
|
89
|
+
"""
|
|
90
|
+
Return the PostgreSQL server version as an integer
|
|
91
|
+
(e.g. 150002 for 15.2, 130008 for 13.8).
|
|
92
|
+
Returns 0 when the version cannot be determined.
|
|
93
|
+
"""
|
|
94
|
+
try:
|
|
95
|
+
row = db.execute(text(
|
|
96
|
+
"SELECT current_setting('server_version_num')::integer AS v"
|
|
97
|
+
)).mappings().first()
|
|
98
|
+
return int(row["v"]) if row else 0
|
|
99
|
+
except Exception:
|
|
100
|
+
return 0
|
|
101
|
+
|
|
102
|
+
|
|
9
103
|
def execute_query(db: Session, query_text, params=None):
|
|
10
104
|
"""
|
|
11
105
|
Execute a query and return the result as a list of dictionaries.
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
{fastpluggy_postgres_tools-0.1.26 → fastpluggy_postgres_tools-0.1.37}/src/routers/__init__.py
RENAMED
|
File without changes
|