-
Notifications
You must be signed in to change notification settings - Fork 1
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Use structured logging in db maintenance lambda
- Loading branch information
Showing
2 changed files
with
24 additions
and
5 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,8 +1,27 @@ | ||
from pg8000.native import Connection | ||
import json | ||
|
||
def handler(event, _context): | ||
config = event['connection'] | ||
max_age = event.get('max_age', '1 WEEK') | ||
config = event.get('connection', {}) | ||
database = config['database'] | ||
|
||
log('Beginning database maintenance', { 'database': database }) | ||
conn = Connection(**config) | ||
|
||
for table in event.get('tables', []): | ||
conn.run(f"DELETE FROM {table} WHERE updated_at < NOW() - interval '1 WEEK'") | ||
conn.run(f"VACUUM {table}") | ||
log('Deleting stale entries', { 'database': database, 'max_age': max_age, 'table': table }) | ||
conn.run(f"DELETE FROM {table} WHERE updated_at < NOW() - interval '{max_age}'") | ||
log('Deleted', { 'database': database, 'table': table, 'rows': conn.row_count }) | ||
|
||
log('Size before vacuuming', { 'database': database, 'table': table, 'bytes': table_size(conn, table) }) | ||
conn.run(f"VACUUM FULL {table}") | ||
log('Size after vacuuming', { 'database': database, 'table': table, 'bytes': table_size(conn, table) }) | ||
|
||
log('Maintenance complete', { 'database': database }) | ||
|
||
def log(message, detail = {}): | ||
print(json.dumps({ 'message': message, 'detail': detail })) | ||
|
||
def table_size(conn, table): | ||
return conn.run(f"SELECT pg_total_relation_size('{table}')")[0][0]; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters