TASK
Implementation
Database migrations version-control schema changes. Each migration has an up() function that applies the change and a down() function that reverses it. A migrations table tracks which versions have been applied so you can apply pending ones or roll back the latest.
Implement a node that manages database schema migrations:
// Apply all pending migrations in version order
{ "type": "migrate", "msg_id": 1 }
-> { "type": "migrations_applied", "in_reply_to": 1,
"count": 2,
"migrations": [
{"version": 1, "name": "create_users", "status": "applied"},
{"version": 2, "name": "add_posts_table", "status": "applied"}
]}
// Rollback the most recently applied migration
{ "type": "rollback", "msg_id": 2 }
-> { "type": "migration_rolled_back", "in_reply_to": 2,
"version": 2, "name": "add_posts_table" }
// Show applied and pending migrations
{ "type": "status", "msg_id": 3 }
-> { "type": "migration_status", "in_reply_to": 3,
"migrations": [
{"version": 1, "name": "create_users", "applied": true},
{"version": 2, "name": "add_posts_table", "applied": false}
]}If a migration fails partway through, the transaction must be rolled back and the migration must NOT be recorded as applied.
Sample Test Cases
Apply pending migrationsTimeout: 10000ms
Input
{
"src": "admin",
"dest": "migrations",
"body": {
"type": "migrate",
"msg_id": 1
}
}Expected Output
{"type": "migrations_applied", "in_reply_to": 1, "count": 2, "migrations": [{"version": 1, "name": "create_users", "status": "applied"}, {"version": 2, "name": "add_posts_table", "status": "applied"}]}Rollback migrationTimeout: 5000ms
Input
{
"src": "admin",
"dest": "migrations",
"body": {
"type": "rollback",
"msg_id": 1
}
}Expected Output
{"type": "migration_rolled_back", "in_reply_to": 1, "version": 2, "name": "add_posts_table"}Hints
Hint 1▾
Migrations are applied in version order; track which ones have run in a migrations table
Hint 2▾
Each migration has an up() function (apply change) and down() function (undo change)
Hint 3▾
Wrap each migration in a transaction; rollback the whole migration on any error
Hint 4▾
migrate applies all pending migrations in order; rollback undoes the most recent one
Hint 5▾
status lists all migrations with applied: true/false
OVERVIEW
Theoretical Hub
Concept overview coming soon
Key Concepts
schema migrationsmigration versioningup/down migrationstransaction safetymigration status
main.py
python
1
2
3
4
5
6
7
8
9
10
11
12
13
#!/usr/bin/env python3
import sys
import json
def main():
# Your implementation here
for line in sys.stdin:
msg = json.loads(line)
print(json.dumps(msg), flush=True)
if __name__ == "__main__":
main()