# VitFit V2 — Migration Plan (V1 → V2) ## Goal Move all existing data from V1's `database.sqlite` to V2 without data loss. V2 uses proper Sequelize migrations going forward — `sync()` is removed entirely. --- ## V1 Schema (what exists today) | Table | Key Fields | |-------|-----------| | Users | id, username, password, role, createdAt, updatedAt | | Videos | id, filename, description, category, createdAt, updatedAt | | Categories | id, name, createdAt, updatedAt | | Workouts | id, video1, video2, video3, video4, number1, number2, number3, number4, name, workoutDate, createdAt, updatedAt | | Timers | id, totalTime, setTime, restTime, moveTime, setCount, exerciseCount, lapCount, createdAt, updatedAt | | CrossfitWorkouts | id, name, workoutDate, workoutItems (JSON string), createdAt, updatedAt | --- ## Migration Strategy ### Step 0 — Video Files Video files at `/home/ubuntu/site/uploads/` do **not** move. V2's `uploads/` folder IS this directory — the new app is deployed alongside (or replacing) V1 at the same path `/home/ubuntu/site/`. The `UPLOADS_DIR` env var in V2's `.env` points to `/home/ubuntu/site/uploads`. No file transfers. No re-uploads. The `filename` values already stored in the `Videos` table remain valid. ### Step 1 — Back Up V1 Database Before deploying V2, back up the existing database: ```bash # On the server (via PuTTY) cp /home/ubuntu/site/database.sqlite /home/ubuntu/site/database.sqlite.v1-backup ``` Then WinSCP a copy to your local machine as an additional backup. V2 will open the live file in place — the backup is the safety net. This preserves all existing data. V2 will open this file and add to it — never recreate from scratch. ### Step 2 — Initialize Sequelize Migrations ```bash npx sequelize-cli init # creates migrations/, seeders/, config/ ``` Set `config/config.json` (or `config/config.js`) to point at the existing SQLite file. ### Step 3 — Create Baseline Migration (V1 Schema) Generate a "baseline" migration that documents the V1 schema as-is. This migration checks if tables exist before creating them (idempotent), so it's safe to run against the already-populated database: ```js // migrations/001-baseline.js module.exports = { up: async (queryInterface, Sequelize) => { // Only creates tables if they don't exist — existing data is untouched const tables = await queryInterface.showAllTables(); if (!tables.includes('Users')) { await queryInterface.createTable('Users', { /* V1 schema */ }); } // ... repeat for each table }, down: async () => { /* no-op for baseline */ } }; ``` After this, `npx sequelize-cli db:migrate` will mark the baseline as done and all future migrations will apply cleanly. ### Step 4 — V2 Schema Additions Each architectural change to the schema is a new numbered migration: | Migration | Change | Reason | |-----------|--------|--------| | `002-add-timer-name.js` | Add `name` column to Timers | Timers need human-readable names in V2 UI | | `003-workout-items-table.js` | Add `WorkoutItems` join table | Future: more than 4 videos per workout | | `004-add-user-refresh-token.js` | Add `refreshToken` column to Users | Token refresh flow | | `005-add-video-mime-type.js` | Add `mimeType` column to Videos | Server-side MIME validation storage | Migrations in `002+` use standard `addColumn` / `createTable` — they do not touch existing data. --- ## Data Compatibility Notes ### Workouts (4-slot model) V1 stores workouts with `video1`–`video4` and `number1`–`number4` as direct columns. This is inflexible but the data is valid. **V2 approach:** Keep the 4-column model as-is for V2. Do not break the schema on day one. The `WorkoutItems` join table migration (`003`) can be added later when the UI is ready to support it. Both models can coexist: - Old workouts: read from `video1`–`video4` columns - New workouts: read from `WorkoutItems` table - A compatibility layer in the API returns the same JSON shape for both ### CrossFit Workouts (`workoutItems` JSON) V1 stores items as a JSON string (SQLite TEXT column). V2 reads it the same way — `JSON.parse()` on read, `JSON.stringify()` on write. No migration needed unless we want to normalize these into rows (not planned for V2). ### Categories V1 seeds 6 categories on startup via `findOrCreate`. V2 migration `001-baseline` includes these as seed data. The seeder won't run if the categories already exist. --- ## Rollback Plan Since V2 copies (not moves) the V1 database, rollback is: 1. Stop V2 server 2. Restart V1 server pointing at its original database file 3. No data loss — V1 database was never touched Additive migrations (columns added, tables created) are also reversible via `db:migrate:undo` on each migration's `down` function. --- ## Deployment Checklist (via PuTTY + WinSCP) ```bash # 1. On your local machine — transfer V2 files via WinSCP to /home/ubuntu/site/ # (overwrite app.js, core/, modules/, public/ — do NOT touch uploads/ or database.sqlite) # 2. SSH via PuTTY, then: cd /home/ubuntu/site # 3. Install dependencies (first deploy only, or when package.json changes) npm install # 4. Create/verify .env file (if not already there via WinSCP) # Required vars: # JWT_SECRET= # DB_PATH=/home/ubuntu/site/database.sqlite # UPLOADS_DIR=/home/ubuntu/site/uploads # PORT=3000 # STORAGE_WARN_BYTES=5368709120 (5 GB default) # 5. Back up DB before first migration run cp database.sqlite database.sqlite.v1-backup # 6. Run migrations npx sequelize-cli db:migrate # 7. Verify DB is reachable node -e "require('./core/db').sequelize.authenticate().then(() => console.log('DB OK'))" # 8. (Re)start with PM2 pm2 restart vitfit # or: pm2 start app.js --name vitfit pm2 save # persist process list across reboots ``` Verify in logs (`pm2 logs vitfit`) that all migrations completed and the server is listening before testing from the iPad.