new revenue getters

This commit is contained in:
samantha42
2026-03-25 15:36:05 +01:00
parent 63be7b9282
commit 4e5b830e75
8 changed files with 98 additions and 49 deletions

View File

@@ -55,7 +55,8 @@ func InitDB(db *sql.DB) {
FOREIGN KEY (company_id) REFERENCES companies(id),
FOREIGN KEY (currency_id) REFERENCES currencies(id),
FOREIGN KEY (category_id) REFERENCES category(id),
FOREIGN KEY (period_id) REFERENCES periods(id)
FOREIGN KEY (period_id) REFERENCES periods(id),
UNIQUE(company_id, category_id, period_id)
);`
if _, err := db.Exec(schema); err != nil {
@@ -63,3 +64,37 @@ func InitDB(db *sql.DB) {
}
fmt.Println("Tables ready")
}
func MigrateAddUniqueToRevenueEntries(db *sql.DB) error {
steps := []string{
// 1. copy existing data into a temp table with the new constraint
`CREATE TABLE IF NOT EXISTS revenue_entries_new (
id INTEGER PRIMARY KEY AUTOINCREMENT,
company_id INTEGER NOT NULL,
currency_id INTEGER NOT NULL,
category_id INTEGER NOT NULL,
period_id INTEGER NOT NULL,
value REAL NOT NULL,
FOREIGN KEY (company_id) REFERENCES companies(id),
FOREIGN KEY (currency_id) REFERENCES currencies(id),
FOREIGN KEY (category_id) REFERENCES category(id),
FOREIGN KEY (period_id) REFERENCES periods(id),
UNIQUE(company_id, category_id, period_id)
)`,
// 2. copy data over
`INSERT OR IGNORE INTO revenue_entries_new
SELECT id, company_id, currency_id, category_id, period_id, value
FROM revenue_entries`,
// 3. drop old table
`DROP TABLE revenue_entries`,
// 4. rename new table
`ALTER TABLE revenue_entries_new RENAME TO revenue_entries`,
}
for _, step := range steps {
if _, err := db.Exec(step); err != nil {
return fmt.Errorf("migration failed: %w", err)
}
}
return nil
}