Skip to content

Commit

Permalink
feat: creating CLI to create and run migrations
Browse files Browse the repository at this point in the history
  • Loading branch information
zoldyzdk committed May 18, 2024
1 parent a0f0d64 commit 90cd986
Show file tree
Hide file tree
Showing 8 changed files with 193 additions and 30 deletions.
5 changes: 0 additions & 5 deletions .env.example
Original file line number Diff line number Diff line change
Expand Up @@ -14,10 +14,5 @@ REDIS_HOST="cache"
REDIS_PORT="6379"
REDIS_PASSWORD="123"

DATABASE_URL=maria:123@tcp(localhost:3306)/petdex?multiStatements=true
PORT=3000
ENVIROMENT=DEVELOPMENT
MIGRATIONS_PATH=migrations

JWT_SECRET=MIGeMA0GCSqGSIb3DQEBAQUAA4GMADCBiAKBgHQ5BWxB9NlRB89pOVY320IISVsSCOLKtGy0nVybrHNdzIhQW64XN8af66SvAN4CG9ZuzH73iGOFUXoMTwy1bDKsoxrRgybEoHA8wZxw0yOItYoQ8HY6fzLJTEmHtMTPLKCqhZe70vEBK/N69dJhZWL0MH4UeQwLgibIrCoPQuhbAgMBAAE

2 changes: 1 addition & 1 deletion api/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ func main() {
}

config.InitConfigs()
sqlxDb, err := sqlx.Connect("mysql", env.DBUrl)
sqlxDb, err := sqlx.Open("mysql", env.DBUrl)

if err != nil {
panic(err)
Expand Down
43 changes: 33 additions & 10 deletions cmd/main.go
Original file line number Diff line number Diff line change
@@ -1,21 +1,44 @@
package main

import (
"pet-dex-backend/v2/infra/db"
"pet-dex-backend/v2/usecase"

"github.com/jmoiron/sqlx"
"fmt"
"pet-dex-backend/v2/pkg/migration"
)

func main() {
var number string
fmt.Println("Migrations CLI")
fmt.Println("Type the number of the command desired:\n1-Migrations UP\n2-Migrations DOWN\n3-Create a new migration\n")
_, err := fmt.Scan(&number)
if err != nil {
fmt.Println("Error while reading the values", err)
}

sqlxDb, err := sqlx.Connect("mysql", "dellis:@/shud")
if number == "1" {
fmt.Println("Running Migrations UP...")
migration.Up()
fmt.Println("Migrations executed!")
return
}

if err != nil {
panic(err)
if number == "2" {
fmt.Println("Running Migrations DOWN...")
migration.Down()
fmt.Println("Migrations executed!")
return
}

if number == "3" {
fmt.Println("Type the name of the migration desired:")
var name string
_, err := fmt.Scan(&name)
if err != nil {
fmt.Println("Error while reading the values", err)
}
fmt.Println("Creating a new migration...")
migration.Create(name)
fmt.Println("Migration created!")
}
pr := db.NewPetRepository(sqlxDb)
adoptUseCase := usecase.NewAdoptUseCase(pr)

adoptUseCase.Do()
return
}
8 changes: 3 additions & 5 deletions go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -4,16 +4,12 @@ go 1.21

require (
github.com/golang-jwt/jwt v3.2.2+incompatible
github.com/golang-migrate/migrate/v4 v4.17.1
github.com/google/uuid v1.4.0
github.com/jmoiron/sqlx v1.3.5
github.com/stretchr/testify v1.9.0
)

require (
github.com/lib/pq v1.10.9 // indirect
github.com/mattn/go-sqlite3 v1.14.16 // indirect
)

require (
github.com/stretchr/objx v0.5.2 // indirect
golang.org/x/crypto v0.21.0
Expand All @@ -29,6 +25,8 @@ require (

require (
github.com/fsnotify/fsnotify v1.7.0 // indirect
github.com/hashicorp/errwrap v1.1.0 // indirect
github.com/hashicorp/go-multierror v1.1.1 // indirect
github.com/hashicorp/hcl v1.0.0 // indirect
github.com/magiconair/properties v1.8.7 // indirect
github.com/mitchellh/mapstructure v1.5.0 // indirect
Expand Down
39 changes: 39 additions & 0 deletions go.sum
Original file line number Diff line number Diff line change
@@ -1,7 +1,21 @@
github.com/Azure/go-ansiterm v0.0.0-20230124172434-306776ec8161 h1:L/gRVlceqvL25UVaW/CKtUDjefjrs0SPonmDGUVOYP0=
github.com/Azure/go-ansiterm v0.0.0-20230124172434-306776ec8161/go.mod h1:xomTg63KZ2rFqZQzSB4Vz2SUXa1BpHTVz9L5PTmPC4E=
github.com/Microsoft/go-winio v0.6.1 h1:9/kr64B9VUZrLm5YYwbGtUJnMgqWVOdUAXu6Migciow=
github.com/Microsoft/go-winio v0.6.1/go.mod h1:LRdKpFKfdobln8UmuiYcKPot9D2v6svN5+sAH+4kjUM=
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc h1:U9qPSI2PIWSS1VwoXQT9A3Wy9MM3WgvqSxFWenqJduM=
github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/dhui/dktest v0.4.1 h1:/w+IWuDXVymg3IrRJCHHOkMK10m9aNVMOyD0X12YVTg=
github.com/dhui/dktest v0.4.1/go.mod h1:DdOqcUpL7vgyP4GlF3X3w7HbSlz8cEQzwewPveYEQbA=
github.com/docker/distribution v2.8.2+incompatible h1:T3de5rq0dB1j30rp0sA2rER+m322EBzniBPB6ZIzuh8=
github.com/docker/distribution v2.8.2+incompatible/go.mod h1:J2gT2udsDAN96Uj4KfcMRqY0/ypR+oyYUYmja8H+y+w=
github.com/docker/docker v24.0.9+incompatible h1:HPGzNmwfLZWdxHqK9/II92pyi1EpYKsAqcl4G0Of9v0=
github.com/docker/docker v24.0.9+incompatible/go.mod h1:eEKB0N0r5NX/I1kEveEz05bcu8tLC/8azJZsviup8Sk=
github.com/docker/go-connections v0.4.0 h1:El9xVISelRB7BuFusrZozjnkIM5YnzCViNKohAFqRJQ=
github.com/docker/go-connections v0.4.0/go.mod h1:Gbd7IOopHjR8Iph03tsViu4nIes5XhDvyHbTtUxmeec=
github.com/docker/go-units v0.5.0 h1:69rxXcBk27SvSaaxTtLh/8llcHD8vYHT7WSdRZ/jvr4=
github.com/docker/go-units v0.5.0/go.mod h1:fgPhTUdO+D/Jk86RDLlptpiXQzgHJF7gydDDbaIK4Dk=
github.com/frankban/quicktest v1.14.6 h1:7Xjx+VpznH+oBnejlPUj8oUpdxnVs4f8XU8WnHkI4W8=
github.com/frankban/quicktest v1.14.6/go.mod h1:4ptaffx2x8+WTWXmUCuVU6aPUX1/Mz7zb5vbUoiM6w0=
github.com/fsnotify/fsnotify v1.7.0 h1:8JEhPFa5W2WU7YfeZzPNqzMP6Lwt7L2715Ggo0nosvA=
Expand All @@ -11,12 +25,21 @@ github.com/go-chi/chi/v5 v5.0.11/go.mod h1:DslCQbL2OYiznFReuXYUmQ2hGd1aDpCnlMNIT
github.com/go-sql-driver/mysql v1.6.0/go.mod h1:DCzpHaOWr8IXmIStZouvnhqoel9Qv2LBy8hT2VhHyBg=
github.com/go-sql-driver/mysql v1.7.1 h1:lUIinVbN1DY0xBg0eMOzmmtGoHwWBbvnWubQUrtU8EI=
github.com/go-sql-driver/mysql v1.7.1/go.mod h1:OXbVy3sEdcQ2Doequ6Z5BW6fXNQTmx+9S1MCJN5yJMI=
github.com/gogo/protobuf v1.3.2 h1:Ov1cvc58UF3b5XjBnZv7+opcTcQFZebYjWzi34vdm4Q=
github.com/gogo/protobuf v1.3.2/go.mod h1:P1XiOD3dCwIKUDQYPy72D8LYyHL2YPYrpS2s69NZV8Q=
github.com/golang-jwt/jwt v3.2.2+incompatible h1:IfV12K8xAKAnZqdXVzCZ+TOjboZ2keLg81eXfW3O+oY=
github.com/golang-jwt/jwt v3.2.2+incompatible/go.mod h1:8pz2t5EyA70fFQQSrl6XZXzqecmYZeUEB8OUGHkxJ+I=
github.com/golang-migrate/migrate/v4 v4.17.1 h1:4zQ6iqL6t6AiItphxJctQb3cFqWiSpMnX7wLTPnnYO4=
github.com/golang-migrate/migrate/v4 v4.17.1/go.mod h1:m8hinFyWBn0SA4QKHuKh175Pm9wjmxj3S2Mia7dbXzM=
github.com/google/go-cmp v0.5.9 h1:O2Tfq5qg4qc4AmwVlvv0oLiVAGB7enBSJ2x2DqQFi38=
github.com/google/go-cmp v0.5.9/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY=
github.com/google/uuid v1.4.0 h1:MtMxsa51/r9yyhkyLsVeVt0B+BGQZzpQiTQ4eHZ8bc4=
github.com/google/uuid v1.4.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
github.com/hashicorp/errwrap v1.0.0/go.mod h1:YH+1FKiLXxHSkmPseP+kNlulaMuP3n2brvKWEqk/Jc4=
github.com/hashicorp/errwrap v1.1.0 h1:OxrOeh75EUXMY8TBjag2fzXGZ40LB6IKw45YeGUDY2I=
github.com/hashicorp/errwrap v1.1.0/go.mod h1:YH+1FKiLXxHSkmPseP+kNlulaMuP3n2brvKWEqk/Jc4=
github.com/hashicorp/go-multierror v1.1.1 h1:H5DkEtf6CXdFp0N0Em5UCwQpXMWke8IA0+lD48awMYo=
github.com/hashicorp/go-multierror v1.1.1/go.mod h1:iw975J/qwKPdAO1clOe2L8331t/9/fmwbPZ6JB6eMoM=
github.com/hashicorp/hcl v1.0.0 h1:0Anlzjpi4vEasTeNFn2mLJgTSwt0+6sfsiTG8qcWGx4=
github.com/hashicorp/hcl v1.0.0/go.mod h1:E5yfLk+7swimpb2L/Alb/PJmXilQ/rhwaUYs4T20WEQ=
github.com/jmoiron/sqlx v1.3.5 h1:vFFPA71p1o5gAeqtEAwLU4dnX2napprKtHr7PYIcN3g=
Expand All @@ -35,8 +58,18 @@ github.com/mattn/go-sqlite3 v1.14.16 h1:yOQRA0RpS5PFz/oikGwBEqvAWhWg5ufRz4ETLjwp
github.com/mattn/go-sqlite3 v1.14.16/go.mod h1:2eHXhiwb8IkHr+BDWZGa96P6+rkvnG63S2DGjv9HUNg=
github.com/mitchellh/mapstructure v1.5.0 h1:jeMsZIYE/09sWLaz43PL7Gy6RuMjD2eJVyuac5Z2hdY=
github.com/mitchellh/mapstructure v1.5.0/go.mod h1:bFUtVrKA4DC2yAKiSyO/QUcy7e+RRV2QTWOzhPopBRo=
github.com/moby/term v0.5.0 h1:xt8Q1nalod/v7BqbG21f8mQPqH+xAaC9C3N3wfWbVP0=
github.com/moby/term v0.5.0/go.mod h1:8FzsFHVUBGZdbDsJw/ot+X+d5HLUbvklYLJ9uGfcI3Y=
github.com/morikuni/aec v1.0.0 h1:nP9CBfwrvYnBRgY6qfDQkygYDmYwOilePFkwzv4dU8A=
github.com/morikuni/aec v1.0.0/go.mod h1:BbKIizmSmc5MMPqRYbxO4ZU0S0+P200+tUnFx7PXmsc=
github.com/opencontainers/go-digest v1.0.0 h1:apOUWs51W5PlhuyGyz9FCeeBIOUDA/6nW8Oi/yOhh5U=
github.com/opencontainers/go-digest v1.0.0/go.mod h1:0JzlMkj0TRzQZfJkVvzbP0HBR3IKzErnv2BNG4W4MAM=
github.com/opencontainers/image-spec v1.0.2 h1:9yCKha/T5XdGtO0q9Q9a6T5NUCsTn/DrBg0D7ufOcFM=
github.com/opencontainers/image-spec v1.0.2/go.mod h1:BtxoFyWECRxE4U/7sNtV5W15zMzWCbyJoFRP3s7yZA0=
github.com/pelletier/go-toml/v2 v2.1.0 h1:FnwAJ4oYMvbT/34k9zzHuZNrhlz48GB3/s6at6/MHO4=
github.com/pelletier/go-toml/v2 v2.1.0/go.mod h1:tJU2Z3ZkXwnxa4DPO899bsyIoywizdUvyaeZurnPPDc=
github.com/pkg/errors v0.9.1 h1:FEBLx1zS214owpjy7qsBeixbURkuhQAwrK5UwLGTwt4=
github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0=
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2 h1:Jamvg5psRIccs7FGNTlIRMkT8wgtp5eCXdBlqhYGL6U=
github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
Expand Down Expand Up @@ -77,10 +110,16 @@ golang.org/x/crypto v0.21.0 h1:X31++rzVUdKhX5sWmSOFZxx8UW/ldWx55cbf08iNAMA=
golang.org/x/crypto v0.21.0/go.mod h1:0BP7YvVV9gBbVKyeTG0Gyn+gZm94bibOW5BjDEYAOMs=
golang.org/x/exp v0.0.0-20230905200255-921286631fa9 h1:GoHiUyI/Tp2nVkLI2mCxVkOjsbSXD66ic0XW0js0R9g=
golang.org/x/exp v0.0.0-20230905200255-921286631fa9/go.mod h1:S2oDrQGGwySpoQPVqRShND87VCbxmc6bL1Yd2oYrm6k=
golang.org/x/mod v0.12.0 h1:rmsUpXtvNzj340zd98LZ4KntptpfRHwpFOHG188oHXc=
golang.org/x/mod v0.12.0/go.mod h1:iBbtSCu2XBx23ZKBPSOrRkjjQPZFPuis4dIYUhu/chs=
golang.org/x/net v0.21.0 h1:AQyQV4dYCvJ7vGmJyKki9+PBdyvhkSd8EIx/qb0AYv4=
golang.org/x/net v0.21.0/go.mod h1:bIjVDfnllIU7BJ2DNgfnXvpSvtn8VRwhlsaeUTyUS44=
golang.org/x/sys v0.18.0 h1:DBdB3niSjOA/O0blCZBqDefyWNYveAYMNF1Wum0DYQ4=
golang.org/x/sys v0.18.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
golang.org/x/text v0.14.0 h1:ScX5w1eTa3QqT8oi6+ziP7dTV1S2+ALU0bI+0zXKWiQ=
golang.org/x/text v0.14.0/go.mod h1:18ZOQIKpY8NJVqYksKHtTdi31H5itFRjB5/qKTNYzSU=
golang.org/x/tools v0.13.0 h1:Iey4qkscZuv0VvIt8E0neZjtPVQFSc870HQ448QgEmQ=
golang.org/x/tools v0.13.0/go.mod h1:HvlwmtVNQAhOuCjW7xxvovg8wbNq7LwfXh/k7wXUl58=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
gopkg.in/check.v1 v1.0.0-20190902080502-41f04d3bba15 h1:YR8cESwS4TdDjEe65xsg0ogRM/Nc3DYOhEAlW+xobZo=
gopkg.in/check.v1 v1.0.0-20190902080502-41f04d3bba15/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
Expand Down
3 changes: 2 additions & 1 deletion infra/config/env.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,10 +6,11 @@ var env *envconfig

type envconfig struct {
DBUrl string `mapstructure:"DATABASE_URL"`
DBUrl_Migration string `mapstructure:"MIGRATION_DATABASE_URL"`
PORT string `mapstructure:"PORT"`
ENV string `mapstructure:"ENVIRONMENT"`
MIGRATIONS_PATH string `mapstructure:"MIGRATIONS_PATH"`
JWT_SECRET string `mapstructure:"JWT_SECRET"`
JWT_SECRET string `mapstructure:"JWT_SECRET"`
}

func GetEnvConfig() *envconfig {
Expand Down
20 changes: 12 additions & 8 deletions migrations/20240508222543_init_db.down.sql
Original file line number Diff line number Diff line change
@@ -1,15 +1,19 @@
drop table if exists addresses cascade;
SET FOREIGN_KEY_CHECKS = 0;

drop table if exists breeds cascade;
drop table if exists vaccines cascade;

drop table if exists legal_person cascade;
drop table if exists pets_image cascade;

drop table if exists person cascade;
drop table if exists pets cascade;

drop table if exists breeds cascade;

drop table if exists pet_image cascade;
drop table if exists addresses cascade;

drop table if exists vaccines cascade;
drop table if exists legal_persons cascade;

drop table if exists pets cascade;
drop table if exists users cascade;

drop table if exists person cascade;

drop table if exists users cascade;
SET FOREIGN_KEY_CHECKS = 1;
103 changes: 103 additions & 0 deletions pkg/migration/migration.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,103 @@
package migration

import (
"database/sql"
"fmt"
_ "github.com/go-sql-driver/mysql"
"github.com/golang-migrate/migrate/v4"
"github.com/golang-migrate/migrate/v4/database/mysql"
_ "github.com/golang-migrate/migrate/v4/source/file"
"log"
"os"
"pet-dex-backend/v2/infra/config"
"time"
)

func Up() {
env, err := config.LoadEnv("../")
if err != nil {
log.Fatalf("Failed to load .env file: %v\n", err)
}
fmt.Println(env.DBUrl_Migration)
db, err := sql.Open("mysql", env.DBUrl_Migration)
if err != nil {
log.Fatalf("Failed connecting to the database: %v\n", err)
}
defer func() {
if err := db.Close(); err != nil {
log.Fatal(err)
}
}()
driver, _ := mysql.WithInstance(db, &mysql.Config{})
migration, err := migrate.NewWithDatabaseInstance(
"file://migrations",
"mysql",
driver,
)
if err != nil {
panic(err)
}
err = migration.Up()
if err != nil {
log.Fatalf("Failed on running migrations up: %v\n", err)
return
}
}

func Down() {
env, err := config.LoadEnv("../")
if err != nil {
log.Fatalf("Failed to load .env file: %v\n", err)
}
fmt.Println(env.DBUrl_Migration)
db, err := sql.Open("mysql", env.DBUrl_Migration)
if err != nil {
log.Fatalf("Failed connecting to the database: %v\n", err)
}
defer func() {
if err := db.Close(); err != nil {
log.Fatal(err)
}
}()
driver, _ := mysql.WithInstance(db, &mysql.Config{})
migration, err := migrate.NewWithDatabaseInstance(
"file://migrations",
"mysql",
driver,
)
if err != nil {
panic(err)
}
err = migration.Down()
if err != nil {
log.Fatalf("Failed on running migrations down: %v\n", err)
return
}

}

func Create(name string) {
path, err := config.LoadEnv("../../")
if err != nil {
fmt.Println("Error loading the .env file:", err)
}
data := time.Now()
timestamp := data.Format("20060102150405")
fmt.Println("Current date and time: ", timestamp)
fileNameDown := fmt.Sprintf("%s/%s_%s.down.sql", path.MIGRATIONS_PATH, timestamp, name)
fileNameUp := fmt.Sprintf("%s/%s_%s.up.sql", path.MIGRATIONS_PATH, timestamp, name)
// Create the file
fileDown, err := os.Create(fileNameDown)
if err != nil {
fmt.Println("Error creating down file:", err)
return
}
defer fileDown.Close()

fileUp, err := os.Create(fileNameUp)
if err != nil {
fmt.Println("Error creating up file:", err)
return
}
defer fileUp.Close()
}

0 comments on commit 90cd986

Please sign in to comment.