Initial commit: Эфир мессенджер
This commit is contained in:
46
internal/repository/sqlite/migrate.go
Normal file
46
internal/repository/sqlite/migrate.go
Normal file
@@ -0,0 +1,46 @@
|
||||
package sqlite
|
||||
|
||||
import (
|
||||
"database/sql"
|
||||
"fmt"
|
||||
"io/ioutil"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
)
|
||||
|
||||
func RunMigrations(db *sql.DB, migrationsPath string) error {
|
||||
// Находим все .up.sql файлы
|
||||
files, err := filepath.Glob(filepath.Join(migrationsPath, "*.up.sql"))
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to find migrations: %w", err)
|
||||
}
|
||||
|
||||
for _, file := range files {
|
||||
fmt.Printf("Applying migration: %s\n", file)
|
||||
|
||||
content, err := ioutil.ReadFile(file)
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to read migration file %s: %w", file, err)
|
||||
}
|
||||
|
||||
// Разделяем SQL statements по точке с запятой
|
||||
statements := strings.Split(string(content), ";")
|
||||
|
||||
for _, stmt := range statements {
|
||||
stmt = strings.TrimSpace(stmt)
|
||||
if stmt == "" {
|
||||
continue
|
||||
}
|
||||
|
||||
// Выполняем SQL
|
||||
if _, err := db.Exec(stmt); err != nil {
|
||||
// Игнорируем ошибку "table already exists"
|
||||
if !strings.Contains(err.Error(), "already exists") {
|
||||
return fmt.Errorf("failed to execute migration %s: %w\nSQL: %s", file, err, stmt)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
Reference in New Issue
Block a user