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,200 @@
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
+
10
+ from fastpluggy.core.menu.decorator import menu_entry
11
+
12
+ replication_router = APIRouter(prefix="/replication", tags=["postgres_replication"])
13
+
14
+
15
+ def get_replication_status(db: Session):
16
+ """
17
+ Get replication status from pg_stat_replication
18
+ """
19
+ query = text("""
20
+ SELECT
21
+ application_name,
22
+ client_addr,
23
+ state,
24
+ sync_state,
25
+ pg_wal_lsn_diff(pg_current_wal_lsn(), sent_lsn) AS write_lag_bytes,
26
+ pg_wal_lsn_diff(pg_current_wal_lsn(), write_lsn) AS flush_lag_bytes,
27
+ pg_wal_lsn_diff(pg_current_wal_lsn(), flush_lsn) AS replay_lag_bytes,
28
+ pg_size_pretty(pg_wal_lsn_diff(pg_current_wal_lsn(), sent_lsn)) AS write_lag,
29
+ pg_size_pretty(pg_wal_lsn_diff(pg_current_wal_lsn(), write_lsn)) AS flush_lag,
30
+ pg_size_pretty(pg_wal_lsn_diff(pg_current_wal_lsn(), flush_lsn)) AS replay_lag,
31
+ CASE
32
+ WHEN pg_wal_lsn_diff(pg_current_wal_lsn(), flush_lsn) > 50000000 THEN 'error'
33
+ WHEN pg_wal_lsn_diff(pg_current_wal_lsn(), flush_lsn) > 10000000 THEN 'warning'
34
+ ELSE 'ok'
35
+ END AS status
36
+ FROM pg_stat_replication
37
+ """)
38
+
39
+ try:
40
+
41
+ result = db.execute(query).mappings()
42
+ return [dict(row) for row in result]
43
+ except Exception as e:
44
+ # This might fail if not running on a primary server
45
+ return []
46
+
47
+
48
+ def get_replication_slots(db: Session):
49
+ """
50
+ Get replication slots from pg_replication_slots
51
+ """
52
+ query = text("""
53
+ SELECT
54
+ slot_name,
55
+ plugin,
56
+ slot_type,
57
+ active,
58
+ restart_lsn,
59
+ pg_size_pretty(pg_wal_lsn_diff(pg_current_wal_lsn(), restart_lsn)) AS retained_size
60
+ FROM pg_replication_slots
61
+ """)
62
+
63
+ try:
64
+
65
+ result = db.execute(query).mappings()
66
+ return [dict(row) for row in result]
67
+ except Exception as e:
68
+ # This might fail if not running on a primary server
69
+ return []
70
+
71
+
72
+ def get_backup_history(db: Session, limit: int = 10):
73
+ """
74
+ Get backup history from pg_backup_history if it exists
75
+ This is a placeholder - in a real implementation, you would need to
76
+ create this table or integrate with a backup tool
77
+ """
78
+ # Check if pg_backup_history table exists
79
+ check_query = text("""
80
+ SELECT EXISTS (
81
+ SELECT FROM information_schema.tables
82
+ WHERE table_schema = 'public'
83
+ AND table_name = 'pg_backup_history'
84
+ ) AS table_exists
85
+ """)
86
+
87
+ try:
88
+
89
+ result = db.execute(check_query).mappings().first()
90
+ if not result or not result["table_exists"]:
91
+ return []
92
+
93
+ # If table exists, query backup history
94
+ query = text(f"""
95
+ SELECT
96
+ backup_id,
97
+ backup_type,
98
+ start_time,
99
+ end_time,
100
+ size_bytes,
101
+ pg_size_pretty(size_bytes) AS size,
102
+ status,
103
+ location
104
+ FROM pg_backup_history
105
+ ORDER BY start_time DESC
106
+ LIMIT {limit}
107
+ """)
108
+
109
+ result = db.execute(query).mappings()
110
+ return [dict(row) for row in result]
111
+ except Exception as e:
112
+ # This might fail if the table doesn't exist
113
+ return []
114
+
115
+
116
+ @replication_router.get("")
117
+ @menu_entry(
118
+ label="Replication & Backups",
119
+ icon="fa fa-sync",
120
+ parent="postgres_tools"
121
+ )
122
+ async def get_replication_view(
123
+ request: Request,
124
+ db=Depends(get_db),
125
+ view_builder=Depends(get_view_builder)
126
+ ):
127
+ """
128
+ Get the PostgreSQL replication and backup status view
129
+ """
130
+ # Get replication and backup data
131
+ replication_status = get_replication_status(db)
132
+ replication_slots = get_replication_slots(db)
133
+ backup_history = get_backup_history(db)
134
+
135
+ # Create widgets
136
+ widgets = []
137
+
138
+ # Add a card for replication status summary
139
+ is_primary = True
140
+ try:
141
+ # Check if this is a primary server
142
+ query = text("SELECT pg_is_in_recovery()")
143
+
144
+ result = db.execute(query).scalar()
145
+ is_primary = not result
146
+ except Exception:
147
+ is_primary = False
148
+
149
+ if is_primary:
150
+ status_card = CardWidget(
151
+ title="Replication Status",
152
+ content=f"This is a primary server with {len(replication_status)} active replicas."
153
+ )
154
+ else:
155
+ status_card = CardWidget(
156
+ title="Replication Status",
157
+ content="This is a replica server."
158
+ )
159
+
160
+ widgets.append(status_card)
161
+
162
+ # Add tables for replication status and slots if this is a primary
163
+ if is_primary and replication_status:
164
+ replication_table = TableWidget(
165
+ title="Replication Status",
166
+ endpoint="/postgres/replication",
167
+ data=replication_status,
168
+ description="Replication lag > 10MB is highlighted in yellow, > 50MB in red."
169
+ )
170
+ widgets.append(replication_table)
171
+
172
+ if is_primary and replication_slots:
173
+ slots_table = TableWidget(
174
+ title="Replication Slots",
175
+ endpoint="/postgres/replication",
176
+ data=replication_slots
177
+ )
178
+ widgets.append(slots_table)
179
+
180
+ # Add a table for backup history if available
181
+ if backup_history:
182
+ backup_table = TableWidget(
183
+ title="Backup History",
184
+ endpoint="/postgres/replication",
185
+ data=backup_history
186
+ )
187
+ widgets.append(backup_table)
188
+ else:
189
+ backup_card = CardWidget(
190
+ title="Backup History",
191
+ content="No backup history available. Consider setting up a backup solution and tracking backups in a pg_backup_history table."
192
+ )
193
+ widgets.append(backup_card)
194
+
195
+ # Render the view
196
+ return view_builder.generate(
197
+ request,
198
+ title="PostgreSQL Replication & Backups",
199
+ widgets=widgets
200
+ )
@@ -0,0 +1,78 @@
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
+ sequences_router = APIRouter(prefix="/sequences", tags=["postgres_sequences"])
11
+
12
+
13
+ def get_sequences_data(db: Session):
14
+ query = text("""
15
+ SELECT
16
+ schemaname || '.' || sequencename AS sequence_name,
17
+ last_value,
18
+ max_value,
19
+ COALESCE(max_value - last_value, 0) AS remaining
20
+ FROM pg_sequences
21
+ WHERE schemaname NOT IN ('pg_catalog', 'information_schema')
22
+ ORDER BY remaining ASC
23
+ """)
24
+
25
+
26
+ result = db.execute(query).mappings()
27
+ rows = []
28
+ for row in result:
29
+ last_value = row["last_value"]
30
+ max_value = row["max_value"]
31
+
32
+ if last_value is None or max_value is None or max_value == 0:
33
+ percent_used = 0
34
+ percent_remaining = 100
35
+ else:
36
+ percent_used = (last_value * 100) / max_value
37
+ percent_remaining = 100 - percent_used
38
+
39
+ rows.append({
40
+ "sequence_name": row["sequence_name"],
41
+ "last_value": last_value,
42
+ "max_value": max_value,
43
+ "remaining": row["remaining"],
44
+ "percent_used": round(percent_used, 2),
45
+ "percent_remaining": round(percent_remaining, 2),
46
+ })
47
+ return rows
48
+
49
+
50
+
51
+
52
+ @sequences_router.get("")
53
+ @menu_entry(
54
+ label="Sequences",
55
+ icon="fa fa-list",
56
+ parent="postgres_tools"
57
+ )
58
+ async def get_sequences_view(request: Request, db=Depends(get_db), view_builder=Depends(get_view_builder)):
59
+ """
60
+ Get the PostgreSQL sequences view
61
+ """
62
+ sequences_info = get_sequences_data(db)
63
+ # Create a TableView for sequences
64
+
65
+ table_view = TableWidget(
66
+ title="Postgres Sequences",
67
+ endpoint="/postgres/sequences",
68
+ data=sequences_info
69
+ )
70
+
71
+ # Render the table view
72
+ return view_builder.generate(
73
+ request,
74
+ title="Postgres Sequences",
75
+ widgets=[
76
+ table_view
77
+ ]
78
+ )
@@ -0,0 +1,106 @@
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
+ from ..utils import execute_query_first
10
+
11
+ tables_router = APIRouter(prefix="/tables", tags=["postgres_tables"])
12
+
13
+
14
+ def get_table_statistics(db_manager: Session, schema: str = None, threshold_warn: int = 20, threshold_error: int = 40):
15
+ """
16
+ Get table statistics from the database including bloat estimation
17
+ """
18
+ where_clause = "WHERE schemaname NOT IN ('pg_catalog', 'information_schema')"
19
+ if schema:
20
+ where_clause += f" AND schemaname = '{schema}'"
21
+
22
+ query = f"""
23
+ SELECT
24
+ schemaname,
25
+ relname AS table_name,
26
+ n_live_tup AS live_rows,
27
+ n_dead_tup AS dead_rows,
28
+ ROUND(100.0 * n_dead_tup / GREATEST(n_live_tup + n_dead_tup, 1), 2) AS bloat_percent,
29
+ pg_size_pretty(pg_total_relation_size(relid)) AS total_size,
30
+ pg_total_relation_size(relid) AS total_bytes,
31
+ last_vacuum,
32
+ last_autovacuum,
33
+ last_analyze,
34
+ last_autoanalyze,
35
+ CASE
36
+ WHEN ROUND(100.0 * n_dead_tup / GREATEST(n_live_tup + n_dead_tup, 1), 2) > {threshold_error} THEN 'error'
37
+ WHEN ROUND(100.0 * n_dead_tup / GREATEST(n_live_tup + n_dead_tup, 1), 2) > {threshold_warn} THEN 'warning'
38
+ ELSE 'ok'
39
+ END AS status
40
+ FROM pg_stat_user_tables
41
+ {where_clause}
42
+ ORDER BY bloat_percent DESC
43
+ """
44
+
45
+ return db_manager.execute(text(query))
46
+
47
+
48
+ def check_pgstattuple_extension(db_manager: Session):
49
+ """
50
+ Check if pgstattuple extension is installed
51
+ """
52
+ query = """
53
+ SELECT COUNT(*) AS count
54
+ FROM pg_extension
55
+ WHERE extname = 'pgstattuple'
56
+ """
57
+
58
+ result = execute_query_first(db=db_manager,query_text=query)
59
+ return result["count"] > 0
60
+
61
+
62
+ @tables_router.get("")
63
+ @menu_entry(
64
+ label="Table Statistics",
65
+ icon="fa fa-table",
66
+ parent="postgres_tools"
67
+ )
68
+ async def get_tables_view(
69
+ request: Request,
70
+ db=Depends(get_db),
71
+ view_builder=Depends(get_view_builder),
72
+ schema: str = None,
73
+ threshold_warn: int = 20,
74
+ threshold_error: int = 40
75
+ ):
76
+ """
77
+ Get the PostgreSQL table statistics view
78
+ """
79
+ # Create a connection manager for this request
80
+
81
+ # Check if pgstattuple extension is installed
82
+ has_pgstattuple = check_pgstattuple_extension(db)
83
+
84
+ # Get table statistics
85
+ table_stats = get_table_statistics(db, schema, threshold_warn, threshold_error)
86
+
87
+ # Create a table for table statistics
88
+ table_widget = TableWidget(
89
+ title="Table Statistics & Bloat",
90
+ endpoint="/postgres/tables",
91
+ data=table_stats,
92
+ description=f"Tables with bloat > {threshold_warn}% are highlighted in yellow, > {threshold_error}% in red."
93
+ )
94
+
95
+ # Add a note about pgstattuple if not installed
96
+ if not has_pgstattuple:
97
+ table_widget.description += " For more accurate bloat estimation, install the pgstattuple extension."
98
+
99
+ # Render the view
100
+ return view_builder.generate(
101
+ request,
102
+ title="PostgreSQL Table Statistics & Bloat",
103
+ widgets=[
104
+ table_widget
105
+ ]
106
+ )
@@ -0,0 +1,221 @@
1
+ from fastapi import APIRouter, Depends, Request, HTTPException
2
+ from sqlalchemy import text
3
+ from sqlalchemy.orm import Session
4
+ from pydantic import BaseModel
5
+ from typing import Optional
6
+
7
+ from fastpluggy.core.database import get_db
8
+ from fastpluggy.core.dependency import get_view_builder
9
+ from fastpluggy.core.widgets import TableWidget, ButtonWidget
10
+ from fastpluggy.core.menu.decorator import menu_entry
11
+
12
+ vacuum_router = APIRouter(prefix="/vacuum", tags=["postgres_vacuum"])
13
+
14
+
15
+ class VacuumRequest(BaseModel):
16
+ schema_name: Optional[str] = None
17
+ table_name: Optional[str] = None
18
+ analyze: bool = True
19
+ full: bool = False
20
+
21
+
22
+ def get_table_vacuum_status(db: Session, schema: str = None, days_since_vacuum: int = None):
23
+ """
24
+ Get vacuum status for tables
25
+ """
26
+ where_clause = "WHERE schemaname NOT IN ('pg_catalog', 'information_schema')"
27
+ if schema:
28
+ where_clause += f" AND schemaname = '{schema}'"
29
+ if days_since_vacuum:
30
+ where_clause += f" AND EXTRACT(EPOCH FROM (now() - COALESCE(last_vacuum, last_autovacuum, '1970-01-01'::timestamp)))/86400 > {days_since_vacuum}"
31
+
32
+ query = text(f"""
33
+ SELECT
34
+ schemaname,
35
+ relname,
36
+ last_vacuum,
37
+ last_autovacuum,
38
+ n_dead_tup,
39
+ EXTRACT(EPOCH FROM (now() - COALESCE(last_vacuum, last_autovacuum, '1970-01-01'::timestamp)))/86400 AS days_since_vacuum,
40
+ CASE
41
+ WHEN EXTRACT(EPOCH FROM (now() - COALESCE(last_vacuum, last_autovacuum, '1970-01-01'::timestamp)))/86400 > 30 THEN 'error'
42
+ WHEN EXTRACT(EPOCH FROM (now() - COALESCE(last_vacuum, last_autovacuum, '1970-01-01'::timestamp)))/86400 > 14 THEN 'warning'
43
+ ELSE 'ok'
44
+ END AS status
45
+ FROM pg_stat_user_tables
46
+ {where_clause}
47
+ ORDER BY days_since_vacuum DESC
48
+ """)
49
+
50
+
51
+ result = db.execute(query).mappings()
52
+ return [dict(row) for row in result]
53
+
54
+
55
+ def get_current_vacuum_progress(db: Session):
56
+ """
57
+ Get current vacuum progress
58
+ """
59
+ query = text("""
60
+ SELECT
61
+ a.pid,
62
+ a.datname,
63
+ a.usename,
64
+ p.relid::regclass AS table_name,
65
+ p.phase,
66
+ p.heap_blks_total,
67
+ p.heap_blks_scanned,
68
+ p.heap_blks_vacuumed,
69
+ ROUND(100.0 * p.heap_blks_scanned / NULLIF(p.heap_blks_total, 0), 2) AS percent_complete
70
+ FROM pg_stat_progress_vacuum p
71
+ JOIN pg_stat_activity a ON p.pid = a.pid
72
+ """)
73
+
74
+
75
+ result = db.execute(query).mappings()
76
+ return [dict(row) for row in result]
77
+
78
+
79
+ def get_autovacuum_settings(db: Session):
80
+ """
81
+ Get autovacuum settings
82
+ """
83
+ query = text("""
84
+ SELECT
85
+ name,
86
+ setting,
87
+ unit,
88
+ context
89
+ FROM pg_settings
90
+ WHERE name LIKE 'autovacuum%'
91
+ """)
92
+
93
+
94
+ result = db.execute(query).mappings()
95
+ return [dict(row) for row in result]
96
+
97
+
98
+ def execute_vacuum(db: Session, vacuum_request: VacuumRequest):
99
+ """
100
+ Execute vacuum operation on specified table(s)
101
+ """
102
+ try:
103
+ # Build the vacuum command
104
+ vacuum_cmd = "VACUUM"
105
+ if vacuum_request.full:
106
+ vacuum_cmd += " FULL"
107
+ if vacuum_request.analyze:
108
+ vacuum_cmd += " ANALYZE"
109
+
110
+ # Add table specification if provided
111
+ if vacuum_request.table_name:
112
+ if vacuum_request.schema_name:
113
+ table_spec = f'"{vacuum_request.schema_name}"."{vacuum_request.table_name}"'
114
+ else:
115
+ table_spec = f'"{vacuum_request.table_name}"'
116
+ vacuum_cmd += f" {table_spec}"
117
+
118
+ # Execute the vacuum command
119
+ db.execute(text(vacuum_cmd))
120
+ db.commit()
121
+
122
+ return {
123
+ "success": True,
124
+ "message": f"Vacuum operation completed successfully",
125
+ "command": vacuum_cmd
126
+ }
127
+ except Exception as e:
128
+ db.rollback()
129
+ raise HTTPException(status_code=500, detail=f"Vacuum operation failed: {str(e)}")
130
+
131
+
132
+ @vacuum_router.post("/execute")
133
+ async def trigger_vacuum(
134
+ vacuum_request: VacuumRequest,
135
+ db=Depends(get_db)
136
+ ):
137
+ """
138
+ Trigger a vacuum operation
139
+ """
140
+ result = execute_vacuum(db, vacuum_request)
141
+ return result
142
+
143
+
144
+ @vacuum_router.get("")
145
+ @menu_entry(
146
+ label="Vacuum Status",
147
+ icon="fa fa-broom",
148
+ parent="postgres_tools"
149
+ )
150
+ async def get_vacuum_view(
151
+ request: Request,
152
+ db=Depends(get_db),
153
+ view_builder=Depends(get_view_builder),
154
+ schema: str = None,
155
+ days_since_vacuum: int = None
156
+ ):
157
+ """
158
+ Get the PostgreSQL vacuum status view
159
+ """
160
+ # Get vacuum status data
161
+ vacuum_status = get_table_vacuum_status(db, schema, days_since_vacuum)
162
+ vacuum_progress = get_current_vacuum_progress(db)
163
+ autovacuum_settings = get_autovacuum_settings(db)
164
+
165
+ # Create widgets
166
+ vacuum_status_table = TableWidget(
167
+ title="Table Vacuum Status",
168
+ endpoint="/postgres/vacuum",
169
+ data=vacuum_status,
170
+ description="Tables that haven't been vacuumed in over 14 days are highlighted in yellow, over 30 days in red."
171
+ )
172
+
173
+ # Create a card for vacuum progress if there are any active vacuum processes
174
+ widgets = [vacuum_status_table]
175
+
176
+ if vacuum_progress:
177
+ progress_table = TableWidget(
178
+ title="Current Vacuum Progress",
179
+ endpoint="/postgres/vacuum",
180
+ data=vacuum_progress
181
+ )
182
+ widgets.append(progress_table)
183
+
184
+ # Create a table for autovacuum settings
185
+ settings_table = TableWidget(
186
+ title="Autovacuum Settings",
187
+ endpoint="/postgres/vacuum",
188
+ data=autovacuum_settings
189
+ )
190
+ widgets.append(settings_table)
191
+
192
+ # Add vacuum action buttons
193
+ vacuum_button = ButtonWidget(
194
+ title="Vacuum Operations",
195
+ buttons=[
196
+ {
197
+ "label": "Run VACUUM ANALYZE (All Tables)",
198
+ "endpoint": "/postgres/vacuum/execute",
199
+ "method": "POST",
200
+ "data": {"analyze": True, "full": False},
201
+ "class": "btn-primary",
202
+ "confirm": "Are you sure you want to run VACUUM ANALYZE on all tables? This may take some time."
203
+ },
204
+ {
205
+ "label": "Run VACUUM FULL ANALYZE (All Tables)",
206
+ "endpoint": "/postgres/vacuum/execute",
207
+ "method": "POST",
208
+ "data": {"analyze": True, "full": True},
209
+ "class": "btn-warning",
210
+ "confirm": "Are you sure you want to run VACUUM FULL ANALYZE on all tables? This will lock tables and may take a long time."
211
+ }
212
+ ]
213
+ )
214
+ widgets.append(vacuum_button)
215
+
216
+ # Render the view
217
+ return view_builder.generate(
218
+ request,
219
+ title="PostgreSQL Vacuum/Autovacuum Status",
220
+ widgets=widgets
221
+ )
@@ -0,0 +1,11 @@
1
+ """
2
+ Utility functions for postgres_tools.
3
+ """
4
+
5
+ from .db_utils import execute_query, execute_query_first, execute_command
6
+
7
+ __all__ = [
8
+ 'execute_query',
9
+ 'execute_query_first',
10
+ 'execute_command',
11
+ ]