fastpluggy-postgres-tools 0.1.13__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.

Potentially problematic release.


This version of fastpluggy-postgres-tools might be problematic. Click here for more details.

@@ -0,0 +1,321 @@
1
+ from fastapi import APIRouter, Depends, Request
2
+ from sqlalchemy import text
3
+ from sqlalchemy.orm import Session
4
+ from typing import List, Dict, Any
5
+
6
+ from fastpluggy.core.database import get_db
7
+ from fastpluggy.core.dependency import get_view_builder
8
+ from fastpluggy.core.widgets import TableWidget
9
+ from fastpluggy_plugin.ui_tools.extra_widget.display.card import CardWidget
10
+ from fastpluggy.core.menu.decorator import menu_entry
11
+
12
+ dashboard_router = APIRouter(prefix="/dashboard", tags=["postgres_dashboard"])
13
+
14
+
15
+ def get_cluster_health(db: Session):
16
+ """
17
+ Get overall cluster health status
18
+ """
19
+ # Check for high table bloat
20
+ bloat_query = text("""
21
+ SELECT
22
+ COUNT(*) AS count,
23
+ MAX(ROUND(100.0 * n_dead_tup / GREATEST(n_live_tup + n_dead_tup, 1), 2)) AS max_bloat
24
+ FROM pg_stat_user_tables
25
+ WHERE ROUND(100.0 * n_dead_tup / GREATEST(n_live_tup + n_dead_tup, 1), 2) > 40
26
+ """)
27
+
28
+ # Check for unused indexes
29
+ index_query = text("""
30
+ SELECT COUNT(*) AS count
31
+ FROM pg_stat_user_indexes
32
+ WHERE idx_scan = 0 AND pg_relation_size(indexrelid) > 10000000
33
+ """)
34
+
35
+ # Check for long-running queries
36
+ query_query = text("""
37
+ SELECT COUNT(*) AS count
38
+ FROM pg_stat_activity
39
+ WHERE state = 'active' AND query_start < NOW() - INTERVAL '5 minutes'
40
+ """)
41
+
42
+ # Check for replication lag
43
+ replication_query = text("""
44
+ SELECT
45
+ COUNT(*) AS count,
46
+ MAX(pg_wal_lsn_diff(pg_current_wal_lsn(), flush_lsn)) AS max_lag
47
+ FROM pg_stat_replication
48
+ WHERE pg_wal_lsn_diff(pg_current_wal_lsn(), flush_lsn) > 50000000
49
+ """)
50
+
51
+ alerts = []
52
+ status = "green"
53
+
54
+ try:
55
+
56
+ # Check table bloat
57
+ bloat_result = db.execute(bloat_query).mappings().first()
58
+ if bloat_result and bloat_result["count"] > 0:
59
+ alerts.append({
60
+ "module": "tables",
61
+ "message": f"{bloat_result['count']} tables with bloat > 40% (max: {bloat_result['max_bloat']}%)",
62
+ "severity": "error"
63
+ })
64
+ status = "red"
65
+
66
+ # Check unused indexes
67
+ index_result = db.execute(index_query).mappings().first()
68
+ if index_result and index_result["count"] > 0:
69
+ alerts.append({
70
+ "module": "indexes",
71
+ "message": f"{index_result['count']} unused indexes larger than 10MB",
72
+ "severity": "warning"
73
+ })
74
+ if status == "green":
75
+ status = "yellow"
76
+
77
+ # Check long-running queries
78
+ query_result = db.execute(query_query).mappings().first()
79
+ if query_result and query_result["count"] > 0:
80
+ alerts.append({
81
+ "module": "queries",
82
+ "message": f"{query_result['count']} queries running for more than 5 minutes",
83
+ "severity": "warning"
84
+ })
85
+ if status == "green":
86
+ status = "yellow"
87
+
88
+ # Check replication lag
89
+ try:
90
+ replication_result = db.execute(replication_query).mappings().first()
91
+ if replication_result and replication_result["count"] > 0:
92
+ alerts.append({
93
+ "module": "replication",
94
+ "message": f"{replication_result['count']} replicas with lag > 50MB",
95
+ "severity": "error"
96
+ })
97
+ status = "red"
98
+ except Exception:
99
+ # This might fail if not running on a primary server
100
+ pass
101
+ except Exception as e:
102
+ alerts.append({
103
+ "module": "system",
104
+ "message": f"Error checking cluster health: {str(e)}",
105
+ "severity": "error"
106
+ })
107
+ status = "red"
108
+
109
+ return {
110
+ "status": status,
111
+ "alerts": alerts
112
+ }
113
+
114
+
115
+ def get_recommendations(db: Session):
116
+ """
117
+ Get recommendations for database improvements
118
+ """
119
+ recommendations = []
120
+
121
+ # Check for pgstattuple extension
122
+ pgstattuple_query = text("""
123
+ SELECT COUNT(*) AS count
124
+ FROM pg_extension
125
+ WHERE extname = 'pgstattuple'
126
+ """)
127
+
128
+ # Check for pg_stat_statements extension
129
+ pg_stat_statements_query = text("""
130
+ SELECT COUNT(*) AS count
131
+ FROM pg_extension
132
+ WHERE extname = 'pg_stat_statements'
133
+ """)
134
+
135
+ # Check autovacuum settings
136
+ autovacuum_query = text("""
137
+ SELECT setting::int AS threshold
138
+ FROM pg_settings
139
+ WHERE name = 'autovacuum_vacuum_threshold'
140
+ """)
141
+
142
+ # Check max_connections usage
143
+ connections_query = text("""
144
+ SELECT
145
+ COUNT(*) AS current_connections,
146
+ (SELECT setting::int FROM pg_settings WHERE name = 'max_connections') AS max_connections
147
+ """)
148
+
149
+ try:
150
+
151
+ # Check pgstattuple extension
152
+ pgstattuple_result = db.execute(pgstattuple_query).mappings().first()
153
+ if pgstattuple_result and pgstattuple_result["count"] == 0:
154
+ recommendations.append({
155
+ "type": "extension",
156
+ "message": "Install pgstattuple for accurate bloat metrics",
157
+ "action": "CREATE EXTENSION pgstattuple;"
158
+ })
159
+
160
+ # Check pg_stat_statements extension
161
+ pg_stat_statements_result = db.execute(pg_stat_statements_query).mappings().first()
162
+ if pg_stat_statements_result and pg_stat_statements_result["count"] == 0:
163
+ recommendations.append({
164
+ "type": "extension",
165
+ "message": "Enable pg_stat_statements for query analysis",
166
+ "action": "CREATE EXTENSION pg_stat_statements;"
167
+ })
168
+
169
+ # Check autovacuum settings
170
+ autovacuum_result = db.execute(autovacuum_query).mappings().first()
171
+ if autovacuum_result and autovacuum_result["threshold"] > 50:
172
+ recommendations.append({
173
+ "type": "setting",
174
+ "message": "Lower autovacuum_vacuum_threshold for more frequent vacuuming",
175
+ "action": "ALTER SYSTEM SET autovacuum_vacuum_threshold = 50;"
176
+ })
177
+
178
+ # Check max_connections usage
179
+ connections_result = db.execute(connections_query).mappings().first()
180
+ if connections_result:
181
+ current = connections_result["current_connections"]
182
+ maximum = connections_result["max_connections"]
183
+ if current > 0.8 * maximum:
184
+ recommendations.append({
185
+ "type": "setting",
186
+ "message": f"Current connections ({current}) approaching max_connections ({maximum})",
187
+ "action": "ALTER SYSTEM SET max_connections = 200; # Adjust as needed"
188
+ })
189
+ except Exception as e:
190
+ recommendations.append({
191
+ "type": "error",
192
+ "message": f"Error generating recommendations: {str(e)}",
193
+ "action": "Check database connection and permissions"
194
+ })
195
+
196
+ return recommendations
197
+
198
+
199
+ def get_metrics_summary(db: Session):
200
+ """
201
+ Get summary metrics for the dashboard
202
+ """
203
+ metrics = {}
204
+
205
+ # Get average table bloat
206
+ bloat_query = text("""
207
+ SELECT AVG(ROUND(100.0 * n_dead_tup / GREATEST(n_live_tup + n_dead_tup, 1), 2)) AS avg_bloat
208
+ FROM pg_stat_user_tables
209
+ WHERE n_live_tup + n_dead_tup > 0
210
+ """)
211
+
212
+ # Get average query latency if pg_stat_statements is available
213
+ latency_query = text("""
214
+ SELECT EXISTS (
215
+ SELECT 1 FROM pg_extension WHERE extname = 'pg_stat_statements'
216
+ ) AS has_pg_stat_statements
217
+ """)
218
+
219
+ latency_data_query = text("""
220
+ SELECT AVG(mean_time) AS avg_latency
221
+ FROM pg_stat_statements
222
+ """)
223
+
224
+ # Get autovacuum runs per day (estimated)
225
+ vacuum_query = text("""
226
+ SELECT COUNT(*) AS table_count
227
+ FROM pg_stat_user_tables
228
+ WHERE last_autovacuum > NOW() - INTERVAL '24 hours'
229
+ """)
230
+
231
+ try:
232
+
233
+ # Get average table bloat
234
+ bloat_result = db.execute(bloat_query).mappings().first()
235
+ if bloat_result:
236
+ metrics["bloat_avg"] = round(bloat_result["avg_bloat"] or 0, 2)
237
+
238
+ # Check if pg_stat_statements is available
239
+ latency_check = db.execute(latency_query).mappings().first()
240
+ if latency_check and latency_check["has_pg_stat_statements"]:
241
+ # Get average query latency
242
+ latency_result = db.execute(latency_data_query).mappings().first()
243
+ if latency_result:
244
+ metrics["query_latency_avg"] = round(latency_result["avg_latency"] or 0, 2)
245
+
246
+ # Get autovacuum runs per day
247
+ vacuum_result = db.execute(vacuum_query).mappings().first()
248
+ if vacuum_result:
249
+ metrics["vacuum_runs_24h"] = vacuum_result["table_count"]
250
+ except Exception as e:
251
+ metrics["error"] = str(e)
252
+
253
+ return metrics
254
+
255
+
256
+ @dashboard_router.get("")
257
+ @menu_entry(
258
+ label="Dashboard",
259
+ icon="fa fa-tachometer-alt",
260
+ parent="postgres_tools"
261
+ )
262
+ async def get_dashboard_view(
263
+ request: Request,
264
+ db=Depends(get_db),
265
+ view_builder=Depends(get_view_builder)
266
+ ):
267
+ """
268
+ Get the PostgreSQL global dashboard view
269
+ """
270
+ # Get dashboard data
271
+ health = get_cluster_health(db)
272
+ recommendations = get_recommendations(db)
273
+ metrics = get_metrics_summary(db)
274
+
275
+ # Create widgets
276
+ status_icon = "✅" if health["status"] == "green" else "⚠️" if health["status"] == "yellow" else "❌"
277
+
278
+ health_card = CardWidget(
279
+ title=f"Global Health: {status_icon} {health['status'].capitalize()}",
280
+ content="Your PostgreSQL database is healthy." if health["status"] == "green" else
281
+ "Your PostgreSQL database has some warnings." if health["status"] == "yellow" else
282
+ "Your PostgreSQL database has critical issues that need attention."
283
+ )
284
+
285
+ # Create alerts table if there are any alerts
286
+ widgets = [health_card]
287
+
288
+ if health["alerts"]:
289
+ alerts_table = TableWidget(
290
+ title="Active Alerts",
291
+ endpoint="/postgres/dashboard",
292
+ data=health["alerts"]
293
+ )
294
+ widgets.append(alerts_table)
295
+
296
+ # Create recommendations table
297
+ if recommendations:
298
+ recommendations_table = TableWidget(
299
+ title="Recommendations",
300
+ endpoint="/postgres/dashboard",
301
+ data=recommendations
302
+ )
303
+ widgets.append(recommendations_table)
304
+
305
+ # Create metrics summary card
306
+ metrics_content = "Key Metrics:\n"
307
+ for key, value in metrics.items():
308
+ metrics_content += f"- {key.replace('_', ' ').title()}: {value}\n"
309
+
310
+ metrics_card = CardWidget(
311
+ title="Metrics Summary",
312
+ content=metrics_content
313
+ )
314
+ widgets.append(metrics_card)
315
+
316
+ # Render the view
317
+ return view_builder.generate(
318
+ request,
319
+ title="PostgreSQL Global Dashboard",
320
+ widgets=widgets
321
+ )
@@ -0,0 +1,142 @@
1
+ from fastapi import APIRouter, Depends, Request
2
+ from sqlalchemy import text
3
+ from sqlalchemy.orm import Session
4
+
5
+ from fastpluggy.core.database import get_db
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
9
+ from fastpluggy.core.menu.decorator import menu_entry
10
+
11
+ db_size_router = APIRouter(prefix="/db/size", tags=["postgres_db_size"])
12
+
13
+
14
+ def get_total_db_size(db: Session):
15
+ query = text("""
16
+ SELECT
17
+ pg_size_pretty(pg_database_size(current_database())) AS total_size,
18
+ pg_database_size(current_database()) AS total_bytes
19
+ """)
20
+
21
+ result = db.execute(query).mappings().first()
22
+ return {
23
+ "total_size": result["total_size"],
24
+ "total_bytes": result["total_bytes"]
25
+ }
26
+
27
+
28
+ def get_schema_sizes(db: Session, include_system: bool = False):
29
+ where_clause = ""
30
+ if not include_system:
31
+ where_clause = "WHERE nspname NOT LIKE 'pg_%' AND nspname != 'information_schema'"
32
+
33
+ query = text(f"""
34
+ SELECT
35
+ nspname AS schema,
36
+ pg_size_pretty(SUM(pg_total_relation_size(c.oid))) AS size,
37
+ SUM(pg_total_relation_size(c.oid)) AS bytes
38
+ FROM pg_class c
39
+ JOIN pg_namespace n ON c.relnamespace = n.oid
40
+ {where_clause}
41
+ GROUP BY nspname
42
+ ORDER BY SUM(pg_total_relation_size(c.oid)) DESC
43
+ """)
44
+
45
+ result = db.execute(query).mappings()
46
+ return [dict(row) for row in result]
47
+
48
+
49
+ def get_tablespace_sizes(db: Session):
50
+ query = text("""
51
+ SELECT
52
+ spcname,
53
+ pg_size_pretty(pg_tablespace_size(spc.oid)) AS size,
54
+ pg_tablespace_size(spc.oid) AS bytes
55
+ FROM pg_tablespace spc
56
+ """)
57
+
58
+ result = db.execute(query).mappings()
59
+ return [dict(row) for row in result]
60
+
61
+
62
+ def get_largest_tables(db: Session, limit: int = 20, schema: str = None):
63
+ where_clause = ""
64
+ if schema:
65
+ where_clause = f"WHERE schemaname = '{schema}'"
66
+
67
+ query = text(f"""
68
+ SELECT
69
+ schemaname,
70
+ relname,
71
+ pg_size_pretty(pg_total_relation_size(relid)) AS total_size,
72
+ pg_size_pretty(pg_relation_size(relid)) AS table_size,
73
+ pg_size_pretty(pg_total_relation_size(relid) - pg_relation_size(relid)) AS index_size,
74
+ pg_total_relation_size(relid) AS total_bytes
75
+ FROM pg_stat_user_tables
76
+ {where_clause}
77
+ ORDER BY pg_total_relation_size(relid) DESC
78
+ LIMIT {limit}
79
+ """)
80
+
81
+ result = db.execute(query).mappings()
82
+ return [dict(row) for row in result]
83
+
84
+
85
+ @db_size_router.get("")
86
+ @menu_entry(
87
+ label="Database Size",
88
+ icon="fa fa-database",
89
+ parent="postgres_tools"
90
+ )
91
+ async def get_db_size_view(
92
+ request: Request,
93
+ db=Depends(get_db),
94
+ view_builder=Depends(get_view_builder),
95
+ include_system: bool = False,
96
+ schema: str = None
97
+ ):
98
+ """
99
+ Get the PostgreSQL database size view
100
+ """
101
+ # Get database size information
102
+ total_size = get_total_db_size(db)
103
+ schema_sizes = get_schema_sizes(db, include_system)
104
+ tablespace_sizes = get_tablespace_sizes(db)
105
+ largest_tables = get_largest_tables(db, schema=schema)
106
+
107
+ # Create a summary card
108
+ summary_card = CardWidget(
109
+ title="Database Size Summary",
110
+ content=f"Total Database Size: {total_size['total_size']}"
111
+ )
112
+
113
+ # Create tables for different size metrics
114
+ schema_table = TableWidget(
115
+ title="Schema Sizes",
116
+ endpoint="/postgres/db/size",
117
+ data=schema_sizes
118
+ )
119
+
120
+ tablespace_table = TableWidget(
121
+ title="Tablespace Sizes",
122
+ endpoint="/postgres/db/size",
123
+ data=tablespace_sizes
124
+ )
125
+
126
+ largest_tables_table = TableWidget(
127
+ title="Largest Tables",
128
+ endpoint="/postgres/db/size",
129
+ data=largest_tables
130
+ )
131
+
132
+ # Render the view
133
+ return view_builder.generate(
134
+ request,
135
+ title="PostgreSQL Database Size",
136
+ widgets=[
137
+ summary_card,
138
+ schema_table,
139
+ tablespace_table,
140
+ largest_tables_table
141
+ ]
142
+ )
@@ -0,0 +1,75 @@
1
+ from fastapi import APIRouter, Depends, Request
2
+ from sqlalchemy import text
3
+ from sqlalchemy.orm import Session
4
+
5
+ from fastpluggy.core.database import get_db
6
+ from fastpluggy.core.dependency import get_view_builder
7
+ from fastpluggy.core.widgets import TableWidget
8
+ from fastpluggy.core.menu.decorator import menu_entry
9
+
10
+ indexes_router = APIRouter(prefix="/indexes", tags=["postgres_indexes"])
11
+
12
+
13
+ def get_index_usage_statistics(db: Session, schema: str = None, threshold_unused: int = 10):
14
+ """
15
+ Get index usage statistics from the database
16
+ """
17
+ where_clause = "WHERE s.schemaname NOT IN ('pg_catalog', 'information_schema')"
18
+ if schema:
19
+ where_clause += f" AND s.schemaname = '{schema}'"
20
+
21
+ query = text(f"""
22
+ SELECT
23
+ s.schemaname,
24
+ s.relname AS table_name,
25
+ s.indexrelname AS index_name,
26
+ s.idx_scan,
27
+ s.idx_tup_read,
28
+ pg_size_pretty(pg_relation_size(s.indexrelid)) AS index_size,
29
+ pg_relation_size(s.indexrelid) AS index_bytes,
30
+ CASE WHEN s.idx_scan < {threshold_unused} THEN true ELSE false END AS is_unused
31
+ FROM pg_stat_user_indexes s
32
+ {where_clause}
33
+ ORDER BY s.idx_scan ASC, pg_relation_size(s.indexrelid) DESC
34
+ """)
35
+
36
+
37
+ result = db.execute(query).mappings()
38
+ return [dict(row) for row in result]
39
+
40
+
41
+ @indexes_router.get("")
42
+ @menu_entry(
43
+ label="Index Usage",
44
+ icon="fa fa-table",
45
+ parent="postgres_tools"
46
+ )
47
+ async def get_indexes_view(
48
+ request: Request,
49
+ db=Depends(get_db),
50
+ view_builder=Depends(get_view_builder),
51
+ schema: str = None,
52
+ threshold_unused: int = 10
53
+ ):
54
+ """
55
+ Get the PostgreSQL index usage statistics view
56
+ """
57
+ # Get index usage statistics
58
+ index_stats = get_index_usage_statistics(db, schema, threshold_unused)
59
+
60
+ # Create a table for index usage statistics
61
+ index_table = TableWidget(
62
+ title="Index Usage Statistics",
63
+ endpoint="/postgres/indexes",
64
+ data=index_stats,
65
+ description=f"Indexes with fewer than {threshold_unused} scans are highlighted as potentially unused."
66
+ )
67
+
68
+ # Render the view
69
+ return view_builder.generate(
70
+ request,
71
+ title="PostgreSQL Index Usage Statistics",
72
+ widgets=[
73
+ index_table
74
+ ]
75
+ )
@@ -0,0 +1,148 @@
1
+ from fastapi import APIRouter, Depends, Request
2
+ from fastapi.responses import RedirectResponse
3
+ from sqlalchemy import text
4
+ from sqlalchemy.orm import Session
5
+
6
+ from fastpluggy.core.database import get_db
7
+ from fastpluggy.core.dependency import get_view_builder
8
+ from fastpluggy.core.widgets import TableWidget
9
+ from fastpluggy.core.menu.decorator import menu_entry
10
+ from fastpluggy_plugin.ui_tools.extra_widget.display.card import CardWidget
11
+
12
+ from ..utils import execute_query_first, execute_query
13
+
14
+ queries_router = APIRouter(prefix="/queries", tags=["postgres_queries"])
15
+
16
+
17
+ def check_pg_stat_statements(db_manager: Session):
18
+ """
19
+ Check if pg_stat_statements extension is installed
20
+ """
21
+ query = """
22
+ SELECT COUNT(*) AS count
23
+ FROM pg_extension
24
+ WHERE extname = 'pg_stat_statements'
25
+ """
26
+
27
+ result = execute_query_first(db=db_manager,query_text=query)
28
+ print(
29
+ f"pg_stat_statements extension is {'installed' if result['count'] > 0 else 'not installed'}"
30
+ )
31
+ return result["count"] > 0
32
+
33
+
34
+ def get_query_performance_statistics(db_manager: Session, limit: int = 10, include_p95: bool = False):
35
+ """
36
+ Get query performance statistics from the database
37
+ """
38
+ # Check if pg_stat_statements is installed
39
+ has_pg_stat_statements = check_pg_stat_statements(db_manager)
40
+
41
+ if not has_pg_stat_statements:
42
+ return [], False
43
+
44
+ # Query to get performance statistics
45
+ p95_column = ""
46
+ if include_p95:
47
+ p95_column = ", (SELECT percentile_cont(0.95) WITHIN GROUP (ORDER BY total_time/calls) FROM pg_stat_statements) AS p95_time"
48
+
49
+ query = f"""
50
+ SELECT
51
+ query,
52
+ calls,
53
+ total_time,
54
+ mean_time,
55
+ ROUND(total_time / GREATEST(calls, 1), 2) AS avg_time,
56
+ SUBSTRING(query, 1, 100) AS truncated_query
57
+ {p95_column}
58
+ FROM pg_stat_statements
59
+ ORDER BY total_time DESC
60
+ LIMIT :limit
61
+ """
62
+
63
+ result = execute_query(db_manager,query, {"limit": limit})
64
+ return result, True
65
+
66
+
67
+ @queries_router.get("")
68
+ @menu_entry(
69
+ label="Query Performance",
70
+ icon="fa fa-tachometer",
71
+ parent="postgres_tools"
72
+ )
73
+ async def get_queries_view(
74
+ request: Request,
75
+ db=Depends(get_db),
76
+ view_builder=Depends(get_view_builder),
77
+ limit: int = 10,
78
+ include_p95: bool = False
79
+ ):
80
+ """
81
+ Get the PostgreSQL query performance analysis view
82
+ """
83
+ # Create a connection manager for this request
84
+
85
+ # Get query performance statistics
86
+ query_stats, has_extension = get_query_performance_statistics(db, limit, include_p95)
87
+
88
+ if not has_extension:
89
+ # Create a card to show extension installation instructions
90
+ extension_card = CardWidget(
91
+ title="Extension Required",
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
+ """,
98
+ links=[
99
+ {
100
+ "url": request.url_for("install_pg_stat_statements"),
101
+ "text": "Install Extension",
102
+ "type": "primary"
103
+ }
104
+ ]
105
+ )
106
+
107
+ return view_builder.generate(
108
+ request,
109
+ title="PostgreSQL Query Performance Analysis",
110
+ widgets=[extension_card]
111
+ )
112
+
113
+ # Create a table for query performance statistics
114
+ query_table = TableWidget(
115
+ title="Query Performance Statistics",
116
+ endpoint="/postgres/queries",
117
+ data=query_stats,
118
+ description=f"Top {limit} queries by total execution time."
119
+ )
120
+
121
+ # Render the view
122
+ return view_builder.generate(
123
+ request,
124
+ title="PostgreSQL Query Performance Analysis",
125
+ widgets=[query_table]
126
+ )
127
+
128
+
129
+ @queries_router.get("/install-pg-stat-statements", name="install_pg_stat_statements")
130
+ async def install_pg_stat_statements(request: Request, db=Depends(get_db)):
131
+ """
132
+ Install the pg_stat_statements extension
133
+ """
134
+ try:
135
+ # Create a connection manager for this request
136
+
137
+ # SQL command to install the extension
138
+ query = "CREATE EXTENSION IF NOT EXISTS pg_stat_statements;"
139
+
140
+ # Execute the SQL command using our connection manager
141
+ db.execute_command(query)
142
+ except Exception as e:
143
+ # If there's an error, we'll just redirect back to the queries view
144
+ # The error will be shown there if the extension still isn't installed
145
+ print(f"Error installing pg_stat_statements extension: {e}")
146
+
147
+ # Redirect back to the queries view
148
+ return RedirectResponse(url=request.url_for("get_queries_view"))