package service

import (
	"database/sql"
	"fmt"
	"strings"
)

func runMigrations(db *sql.DB, statements []string, ignoreErr func(statement string, err error) bool) error {
	for _, stmt := range statements {
		if _, err := db.Exec(stmt); err != nil {
			if ignoreErr != nil && ignoreErr(stmt, err) {
				continue
			}
			return fmt.Errorf("failed to run migration %q: %w", stmt, err)
		}
	}

	return nil
}

func ignoreSQLiteDuplicateColumn(statement string, err error) bool {
	return strings.Contains(statement, "ALTER TABLE requests ADD COLUMN") &&
		strings.Contains(strings.ToLower(err.Error()), "duplicate column name")
}
