Skip to content

Commit

Permalink
Merge pull request #3 from alexisvisco/1-remove-driver-dependencies
Browse files Browse the repository at this point in the history
1 remove driver dependencies
  • Loading branch information
alexisvisco authored May 24, 2024
2 parents 19dece9 + db2ce9a commit 97ca53b
Show file tree
Hide file tree
Showing 57 changed files with 1,676 additions and 1,113 deletions.
2 changes: 2 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -4,3 +4,5 @@
.idea
migrations
.amigo
!example/pg/.amigo
!example/pg/migrations
3 changes: 2 additions & 1 deletion cmd/context.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package cmd

import (
"github.com/alexisvisco/amigo/pkg/amigo"
"github.com/spf13/cobra"
"github.com/spf13/viper"
)
Expand All @@ -19,7 +20,7 @@ Example:
This command will create a file .amigo/context.yaml with the content:
dsn: "postgres://user:password@host:port/dbname?sslmode=disable"
`,
Run: wrapCobraFunc(func(cmd *cobra.Command, args []string) error {
Run: wrapCobraFunc(func(cmd *cobra.Command, _ amigo.Amigo, args []string) error {
err := viper.WriteConfig()
if err != nil {
return err
Expand Down
86 changes: 51 additions & 35 deletions cmd/create.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,17 +4,21 @@ import (
"fmt"
"github.com/alexisvisco/amigo/pkg/amigo"
"github.com/alexisvisco/amigo/pkg/types"
"github.com/alexisvisco/amigo/pkg/utils"
"github.com/alexisvisco/amigo/pkg/utils/events"
"github.com/alexisvisco/amigo/pkg/utils/logger"
"github.com/gobuffalo/flect"
"github.com/spf13/cobra"
"path"
"path/filepath"
"time"
)

// createCmd represents the create command
var createCmd = &cobra.Command{
Use: "create <name>",
Short: "Create a new migration in the migration folder",
Run: wrapCobraFunc(func(cmd *cobra.Command, args []string) error {
Run: wrapCobraFunc(func(cmd *cobra.Command, am amigo.Amigo, args []string) error {
if len(args) == 0 {
return fmt.Errorf("name is required: amigo create <name>")
}
Expand All @@ -27,68 +31,80 @@ var createCmd = &cobra.Command{
return err
}

migFileType := types.MigrationFileType(cmdCtx.Create.Type)

inUp := ""

if cmdCtx.Create.Dump {
migFileType = types.MigrationFileTypeClassic

dump, err := amigo.DumpSchema(&amigo.DumpSchemaOptions{
DSN: cmdCtx.DSN,
MigrationTableName: cmdCtx.SchemaVersionTable,
PGDumpPath: cmdCtx.PGDumpPath,
Schema: cmdCtx.Create.Schema,
Shell: cmdCtx.ShellPath,
})
dump, err := am.DumpSchema()
if err != nil {
return err
}

inUp += fmt.Sprintf("s.Exec(`%s`)\n", dump)

cmdCtx.Create.Type = "classic"
}

filePath, version, err := amigo.GenerateMigrationFile(amigo.GenerateMigrationFileOptions{
Name: args[0],
Folder: cmdCtx.MigrationFolder,
Driver: getDriver(cmdCtx.DSN),
Package: cmdCtx.PackagePath,
MigType: migFileType,
InUp: inUp,
now := time.Now()
version := now.UTC().Format(utils.FormatTime)
cmdCtx.Create.Version = version

migrationFileName := fmt.Sprintf("%s_%s.go", version, flect.Underscore(args[0]))
file, err := utils.CreateOrOpenFile(filepath.Join(cmdCtx.MigrationFolder, migrationFileName))
if err != nil {
return fmt.Errorf("unable to open/create file: %w", err)
}

err = am.GenerateMigrationFile(&amigo.GenerateMigrationFileParams{
Name: args[0],
Up: inUp,
Down: "",
Type: types.MigrationFileType(cmdCtx.Create.Type),
Now: now,
Writer: file,
})
if err != nil {
return err
}

logger.Info(events.FileAddedEvent{FileName: filePath})
logger.Info(events.FileAddedEvent{FileName: filepath.Join(cmdCtx.MigrationFolder, migrationFileName)})

// create the migrations file where all the migrations will be stored
file, err = utils.CreateOrOpenFile(path.Join(cmdCtx.MigrationFolder, migrationsFile))
if err != nil {
return err
}

err = am.GenerateMigrationsFiles(file)
if err != nil {
return err
}

logger.Info(events.FileModifiedEvent{FileName: path.Join(cmdCtx.MigrationFolder, migrationsFile)})

if cmdCtx.Create.Skip {
connection, _, err := amigo.GetConnection(cmdCtx.DSN)
err = am.ExecuteMain(amigo.MainArgSkipMigration)
if err != nil {
return err
}

_, err = connection.Exec("INSERT INTO "+cmdCtx.SchemaVersionTable+" (version) VALUES ($1)", version)
if err != nil {
return fmt.Errorf("unable to set migration as applied: %w", err)
}

logger.Info(events.SkipMigrationEvent{MigrationVersion: version})
}

err = amigo.GenerateMigrationsFile(cmdCtx.MigrationFolder, cmdCtx.PackagePath,
filepath.Join(cmdCtx.MigrationFolder, migrationsFile))
if err != nil {
return err
}

logger.Info(events.FileModifiedEvent{FileName: filepath.Join(cmdCtx.MigrationFolder, migrationsFile)})

return nil
}),
}

func init() {
rootCmd.AddCommand(createCmd)
cmdCtx.Create.Register(createCmd)
createCmd.Flags().StringVar(&cmdCtx.Create.Type, "type", "change",
"The type of migration to create, possible values are [classic, change]")

createCmd.Flags().BoolVarP(&cmdCtx.Create.Dump, "dump", "d", false,
"dump with pg_dump the current schema and add it to the current migration")

createCmd.Flags().StringVarP(&cmdCtx.Create.DumpSchema, "dump-schema", "s", "public",
"the schema to dump if --dump is set")

createCmd.Flags().BoolVar(&cmdCtx.Create.Skip, "skip", false,
"skip will set the migration as applied without executing it")
}
54 changes: 32 additions & 22 deletions cmd/init.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,66 +4,76 @@ import (
"fmt"
"github.com/alexisvisco/amigo/pkg/amigo"
"github.com/alexisvisco/amigo/pkg/templates"
"github.com/alexisvisco/amigo/pkg/types"
"github.com/alexisvisco/amigo/pkg/utils"
"github.com/alexisvisco/amigo/pkg/utils/events"
"github.com/alexisvisco/amigo/pkg/utils/logger"
"github.com/spf13/cobra"
"os"
"path"
"time"
)

// initCmd represents the init command
var initCmd = &cobra.Command{
Use: "init",
Short: "Initialize migrations folder and add the first migration file",
Run: wrapCobraFunc(func(cmd *cobra.Command, args []string) error {
Run: wrapCobraFunc(func(cmd *cobra.Command, am amigo.Amigo, args []string) error {
if err := cmdCtx.ValidateDSN(); err != nil {
return err
}

err := os.MkdirAll(cmdCtx.MigrationFolder, 0755)
if err != nil {
return fmt.Errorf("unable to create migration folder: %w", err)
}

// create the main file
logger.Info(events.FolderAddedEvent{FolderName: cmdCtx.MigrationFolder})

err = os.MkdirAll(cmdCtx.AmigoFolderPath, 0755)
file, err := utils.CreateOrOpenFile(path.Join(cmdCtx.AmigoFolderPath, "main.go"))
if err != nil {
return fmt.Errorf("unable to create main folder: %w", err)
return fmt.Errorf("unable to open main.go file: %w", err)
}

err = amigo.GenerateMainFile(cmdCtx.AmigoFolderPath, cmdCtx.MigrationFolder)
err = am.GenerateMainFile(file)
if err != nil {
return err
}

logger.Info(events.FileAddedEvent{FileName: path.Join(cmdCtx.AmigoFolderPath, "main.go")})

// create the base schema version table
now := time.Now()
migrationFileName := fmt.Sprintf("%s_create_table_schema_version.go", now.UTC().Format(utils.FormatTime))
file, err = utils.CreateOrOpenFile(path.Join(cmdCtx.MigrationFolder, migrationFileName))
if err != nil {
return fmt.Errorf("unable to open migrations.go file: %w", err)
}

template, err := templates.GetInitCreateTableTemplate(templates.CreateTableData{Name: cmdCtx.SchemaVersionTable})
if err != nil {
return err
}

file, _, err := amigo.GenerateMigrationFile(amigo.GenerateMigrationFileOptions{
Name: "schema_version",
Folder: cmdCtx.MigrationFolder,
Driver: getDriver(cmdCtx.DSN),
Package: cmdCtx.PackagePath,
MigType: "change",
InUp: template,
InDown: "",
err = am.GenerateMigrationFile(&amigo.GenerateMigrationFileParams{
Name: "create_table_schema_version",
Up: template,
Type: types.MigrationFileTypeClassic,
Now: now,
Writer: file,
UseSchemaImport: true,
})
if err != nil {
return err
}
logger.Info(events.FileAddedEvent{FileName: path.Join(cmdCtx.MigrationFolder, migrationFileName)})

logger.Info(events.FileAddedEvent{FileName: file})
// create the migrations file where all the migrations will be stored
file, err = utils.CreateOrOpenFile(path.Join(cmdCtx.MigrationFolder, migrationsFile))
if err != nil {
return err
}

err = amigo.GenerateMigrationsFile(cmdCtx.MigrationFolder, cmdCtx.PackagePath,
path.Join(cmdCtx.MigrationFolder, migrationsFile))
err = am.GenerateMigrationsFiles(file)
if err != nil {
return err
}

logger.Info(events.FileAddedEvent{FileName: path.Join(cmdCtx.AmigoFolderPath, "main.go")})
logger.Info(events.FileAddedEvent{FileName: path.Join(cmdCtx.MigrationFolder, migrationsFile)})

return nil
Expand Down
43 changes: 0 additions & 43 deletions cmd/migrate.go

This file was deleted.

52 changes: 52 additions & 0 deletions cmd/migration.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
package cmd

import (
"github.com/alexisvisco/amigo/pkg/amigo"
"github.com/alexisvisco/amigo/pkg/amigoctx"
"github.com/spf13/cobra"
)

// migrateCmd represents the up command
var migrateCmd = &cobra.Command{
Use: "migrate",
Short: "Apply the database",
Run: wrapCobraFunc(func(cmd *cobra.Command, am amigo.Amigo, args []string) error {
if err := cmdCtx.ValidateDSN(); err != nil {
return err
}

return am.ExecuteMain(amigo.MainArgMigrate)
}),
}

// rollbackCmd represents the down command
var rollbackCmd = &cobra.Command{
Use: "rollback",
Short: "Rollback the database",
Run: wrapCobraFunc(func(cmd *cobra.Command, am amigo.Amigo, args []string) error {
if err := cmdCtx.ValidateDSN(); err != nil {
return err
}

return am.ExecuteMain(amigo.MainArgRollback)
}),
}

func init() {
rootCmd.AddCommand(rollbackCmd)
rootCmd.AddCommand(migrateCmd)

registerBase := func(cmd *cobra.Command, m *amigoctx.Migration) {
cmd.Flags().StringVar(&m.Version, "version", "",
"Apply a specific version format: 20240502083700 or 20240502083700_name.go")
cmd.Flags().BoolVar(&m.DryRun, "dry-run", false, "Run the migrations without applying them")
cmd.Flags().BoolVar(&m.ContinueOnError, "continue-on-error", false,
"Will not rollback the migration if an error occurs")
cmd.Flags().DurationVar(&m.Timeout, "timeout", amigoctx.DefaultTimeout, "The timeout for the migration")
}

registerBase(migrateCmd, cmdCtx.Migration)

registerBase(rollbackCmd, cmdCtx.Migration)
rollbackCmd.Flags().IntVar(&cmdCtx.Migration.Steps, "steps", 1, "The number of steps to rollback")
}
Loading

0 comments on commit 97ca53b

Please sign in to comment.