summaryrefslogtreecommitdiff
path: root/storage/migrate.go
diff options
context:
space:
mode:
authorGrail Finder <wohilas@gmail.com>2024-11-20 13:21:51 +0300
committerGrail Finder <wohilas@gmail.com>2024-11-20 13:21:51 +0300
commit8ae4d075c4d043eae604af9cad0cf5e571420a61 (patch)
tree3b0eb7689a598e25dac67d889e037f3bc08c19a1 /storage/migrate.go
parent74669b58fe7b58b3d2fd4ad88c03890bc53a7a1a (diff)
Feat: migration on startup
Diffstat (limited to 'storage/migrate.go')
-rw-r--r--storage/migrate.go59
1 files changed, 59 insertions, 0 deletions
diff --git a/storage/migrate.go b/storage/migrate.go
new file mode 100644
index 0000000..d97b99d
--- /dev/null
+++ b/storage/migrate.go
@@ -0,0 +1,59 @@
+package storage
+
+import (
+ "embed"
+ "fmt"
+ "io/fs"
+ "strings"
+)
+
+//go:embed migrations/*
+var migrationsFS embed.FS
+
+func (p *ProviderSQL) Migrate() {
+ // Get the embedded filesystem
+ migrationsDir, err := fs.Sub(migrationsFS, "migrations")
+ if err != nil {
+ p.logger.Error("Failed to get embedded migrations directory;", "error", err)
+ }
+ // List all .up.sql files
+ files, err := migrationsFS.ReadDir("migrations")
+ if err != nil {
+ p.logger.Error("Failed to read migrations directory;", "error", err)
+ }
+ // Execute each .up.sql file
+ for _, file := range files {
+ if strings.HasSuffix(file.Name(), ".up.sql") {
+ err := p.executeMigration(migrationsDir, file.Name())
+ if err != nil {
+ p.logger.Error("Failed to execute migration %s: %v", file.Name(), err)
+ }
+ }
+ }
+ p.logger.Info("All migrations executed successfully!")
+}
+
+func (p *ProviderSQL) executeMigration(migrationsDir fs.FS, fileName string) error {
+ // Open the migration file
+ migrationFile, err := migrationsDir.Open(fileName)
+ if err != nil {
+ return fmt.Errorf("failed to open migration file %s: %w", fileName, err)
+ }
+ defer migrationFile.Close()
+ // Read the migration file content
+ migrationContent, err := fs.ReadFile(migrationsDir, fileName)
+ if err != nil {
+ return fmt.Errorf("failed to read migration file %s: %w", fileName, err)
+ }
+ // Execute the migration content
+ return p.executeSQL(migrationContent)
+}
+
+func (p *ProviderSQL) executeSQL(sqlContent []byte) error {
+ // Connect to the database (example using a simple connection)
+ _, err := p.db.Exec(string(sqlContent))
+ if err != nil {
+ return fmt.Errorf("failed to execute SQL: %w", err)
+ }
+ return nil
+}