Jun 24 - Implement devices tracker - Update

This commit is contained in:
Nguyen Ngo
2026-06-24 17:44:38 -04:00
parent 464dc86b0d
commit 2293f88f42
5 changed files with 78 additions and 74 deletions
+25 -22
View File
@@ -1,11 +1,8 @@
"""phase31 — device_registrations table (re-issue of phase30)
"""phase31 — add ios_version and last_seen_at to api_device_tokens
phase30 used op.get_bind() + op.create_table() which is unreliable with
Flask-Migrate and left the table uncreated even though alembic_version
recorded phase30 as applied. This migration re-creates the table using
the same raw-SQL pattern used by every other migration in this project.
CREATE TABLE IF NOT EXISTS is idempotent — safe whether or not the table
was partially created by the broken phase30.
Extends the existing api_device_tokens table (phase7) so the admin
Devices page can show iOS version and time of last app launch.
Drops the unused device_registrations table created by phase30 if it exists.
"""
from alembic import op
@@ -17,23 +14,29 @@ depends_on = None
def upgrade():
# Add ios_version column if it doesn't exist
op.execute("""
CREATE TABLE IF NOT EXISTS device_registrations (
id INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
device_id VARCHAR(64) NOT NULL,
user_id INT NOT NULL,
device_name VARCHAR(255) NOT NULL DEFAULT '',
app_version VARCHAR(32) NOT NULL DEFAULT '',
ios_version VARCHAR(32) NOT NULL DEFAULT '',
registered_at DATETIME NOT NULL,
last_seen_at DATETIME NOT NULL,
CONSTRAINT uq_device_id UNIQUE (device_id),
CONSTRAINT fk_device_reg_user
FOREIGN KEY (user_id) REFERENCES users(id)
ON DELETE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4
ALTER TABLE api_device_tokens
ADD COLUMN IF NOT EXISTS ios_version VARCHAR(20) NULL
""")
# Add last_seen_at column if it doesn't exist
op.execute("""
ALTER TABLE api_device_tokens
ADD COLUMN IF NOT EXISTS last_seen_at DATETIME NULL
""")
# Backfill last_seen_at from registered_at for existing rows
op.execute("""
UPDATE api_device_tokens
SET last_seen_at = registered_at
WHERE last_seen_at IS NULL
""")
# Drop the incorrectly created device_registrations table from phase30 if present
op.execute("DROP TABLE IF EXISTS device_registrations")
def downgrade():
op.execute("DROP TABLE IF EXISTS device_registrations")
op.execute("ALTER TABLE api_device_tokens DROP COLUMN IF EXISTS ios_version")
op.execute("ALTER TABLE api_device_tokens DROP COLUMN IF EXISTS last_seen_at")