Files
apocapoc-api/internal/infrastructure/persistence/sqlite/migrations.go
T
david 10d45fc34e Add COUNTER type with auto-increment and IsNegative field
COUNTER type:
- Only accepts integer values (rejects decimals)
- Auto-increment behavior: each mark adds to existing value
- Supports decrement via negative values (e.g., -2)
- Enforces minimum value of 0 (never negative)
- Default increment is 1 if no value provided

VALUE type:
- Accepts decimal values
- Replaces value (no auto-increment)

IsNegative field:
- New boolean field on Habit entity
- Persisted in database (is_negative column)
- Available in all DTOs and HTTP responses
- Marks habits as "negative" (e.g., candy consumption)

Examples:
- COUNTER: 5 + (-2) = 3, 2 + (-3) = 0, 0 + (-1) = 0
- VALUE: 5000 → 12000 = 12000 (replacement)
2025-11-27 08:58:39 +01:00

71 lines
1.7 KiB
Go

package sqlite
import (
"database/sql"
)
func RunMigrations(db *sql.DB) error {
migrations := []string{
createUsersTable,
createHabitsTable,
createHabitEntriesTable,
createIndexes,
}
for _, migration := range migrations {
if _, err := db.Exec(migration); err != nil {
return err
}
}
return nil
}
const createUsersTable = `
CREATE TABLE IF NOT EXISTS users (
id TEXT PRIMARY KEY,
email TEXT UNIQUE NOT NULL,
password_hash TEXT NOT NULL,
timezone TEXT DEFAULT 'UTC',
created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
updated_at DATETIME DEFAULT CURRENT_TIMESTAMP
);
`
const createHabitsTable = `
CREATE TABLE IF NOT EXISTS habits (
id TEXT PRIMARY KEY,
user_id TEXT NOT NULL,
name TEXT NOT NULL,
description TEXT,
type TEXT CHECK(type IN ('BOOLEAN', 'COUNTER', 'VALUE')),
frequency TEXT CHECK(frequency IN ('DAILY', 'WEEKLY', 'MONTHLY')),
specific_days TEXT,
specific_dates TEXT,
carry_over BOOLEAN DEFAULT 0,
is_negative BOOLEAN DEFAULT 0,
target_value REAL,
created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
archived_at DATETIME,
FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE
);
`
const createHabitEntriesTable = `
CREATE TABLE IF NOT EXISTS habit_entries (
id TEXT PRIMARY KEY,
habit_id TEXT NOT NULL,
scheduled_date DATE NOT NULL,
completed_at DATETIME NOT NULL,
value REAL,
FOREIGN KEY (habit_id) REFERENCES habits(id) ON DELETE CASCADE,
UNIQUE(habit_id, scheduled_date)
);
`
const createIndexes = `
CREATE INDEX IF NOT EXISTS idx_habits_user ON habits(user_id);
CREATE INDEX IF NOT EXISTS idx_habits_active ON habits(user_id, archived_at);
CREATE INDEX IF NOT EXISTS idx_entries_habit ON habit_entries(habit_id);
CREATE INDEX IF NOT EXISTS idx_entries_scheduled ON habit_entries(scheduled_date);
`