Skip to content
Open
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 0 additions & 8 deletions .idea/.gitignore

This file was deleted.

8 changes: 0 additions & 8 deletions .idea/modules.xml

This file was deleted.

15 changes: 0 additions & 15 deletions .idea/protoeditor.xml

This file was deleted.

7 changes: 1 addition & 6 deletions .idea/workout-training-api.iml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

16 changes: 16 additions & 0 deletions docker-compose.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
version: '3.9'

services:
postgres:
container_name: workout_postgres_container
image: postgres:14.5
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

need postgres 17

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

8396dc3 поменял версию

ports:
- 5432:5432
environment:
POSTGRES_DB: "workoutdb"
POSTGRES_PASSWORD: "admin"
volumes:
- pgdata:/var/lib/postgresql/data

volumes:
pgdata:
1 change: 1 addition & 0 deletions go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ require (
github.com/agnivade/levenshtein v1.2.0 // indirect
github.com/cpuguy83/go-md2man/v2 v2.0.5 // indirect
github.com/google/uuid v1.6.0 // indirect
github.com/joho/godotenv v1.5.1
github.com/russross/blackfriday/v2 v2.1.0 // indirect
github.com/sosodev/duration v1.3.1 // indirect
github.com/urfave/cli/v2 v2.27.5 // indirect
Expand Down
2 changes: 2 additions & 0 deletions go.sum
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,8 @@ github.com/gorilla/websocket v1.5.0 h1:PPwGk2jz7EePpoHN/+ClbZu8SPxiqlu12wZP/3sWm
github.com/gorilla/websocket v1.5.0/go.mod h1:YR8l580nyteQvAITg2hZ9XVh4b55+EU/adAjf1fMHhE=
github.com/hashicorp/golang-lru/v2 v2.0.7 h1:a+bsQ5rvGLjzHuww6tVxozPZFVghXaHOwFs4luLUK2k=
github.com/hashicorp/golang-lru/v2 v2.0.7/go.mod h1:QeFd9opnmA6QUJc5vARoKUSoFhyfM2/ZepoAG6RGpeM=
github.com/joho/godotenv v1.5.1 h1:7eLL/+HRGLY0ldzfGMeQkb7vMd0as4CfYvUVzLqw0N0=
github.com/joho/godotenv v1.5.1/go.mod h1:f4LDr5Voq0i2e/R5DDNOoa2zzDfwtkZa6DnEwAbqwq4=
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
github.com/russross/blackfriday/v2 v2.1.0 h1:JIOH55/0cWyOuilr9/qlrm0BSXldqnqwMsf35Ld67mk=
Expand Down
48 changes: 48 additions & 0 deletions internal/askar-postgres/main.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
package askar_postgres

import (
"context"
"database/sql"
_ "database/sql"
"fmt"
"log/slog"
"time"
"workout-training-api/internal/askar-postgres/model"
"workout-training-api/internal/config"
)

type Postgres struct {
*model.Model
}

func New(conf *config.PostgresConfig, logger *slog.Logger) (*Postgres, error) {
db, err := NewDatabase(conf)
if err != nil {
return nil, err
}

return &Postgres{
Model: model.New(conf, logger.With(slog.String("module", "model")), db),
}, nil
}

func NewDatabase(conf *config.PostgresConfig) (*sql.DB, error) {
psqlInfo := fmt.Sprintf(
"host=%s port=%d user=%s password=%s dbname=%s sslmode=disable",
conf.Host, conf.Port, conf.User, conf.Password, conf.Name,
)
db, err := sql.Open("postgres", psqlInfo)
if err != nil {
return nil, err
}

ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()

err = db.PingContext(ctx)
if err != nil {
return nil, err
}

return db, nil
}
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
DROP TABLE IF EXISTS exercises;
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
CREATE TABLE IF NOT EXISTS exercises (
id bigserial PRIMARY KEY,
name VARCHAR(255) NOT NULL,
description TEXT,
repetitions INTEGER NOT NULL,
sets INTEGER NOT NULL,
weight INTEGER NOT NULL,
muscle_groups text [] NOT NULL,
categories text [] NOT NULL,
created_at TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP
);
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
DROP TABLE IF EXISTS workouts;
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
CREATE TABLE IF NOT EXISTS workouts (
id bigserial PRIMARY KEY,
name VARCHAR(255) NOT NULL,
status VARCHAR(255) NOT NULL,
scheduled_times TIMESTAMP WITH TIME ZONE[] NOT NULL,
created_at TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP
);

Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
DROP TABLE IF EXISTS exercise_workout;
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
CREATE TABLE IF NOT EXISTS exercise_workout (
id bigserial PRIMARY KEY,
exercise_id BIGINT NOT NULL,
workout_id BIGINT NOT NULL,
created_at TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP,
CONSTRAINT fk_exercise
FOREIGN KEY (exercise_id)
REFERENCES exercises (id)
ON DELETE CASCADE,
CONSTRAINT fk_workout
FOREIGN KEY (workout_id)
REFERENCES workouts (id)
ON DELETE CASCADE
);
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
DROP INDEX IF EXISTS idx_exercise_workout_exercise_id;
DROP INDEX IF EXISTS idx_exercise_workout_workout_id;

Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
CREATE INDEX IF NOT EXISTS idx_exercise_workout_exercise_id ON exercise_workout (exercise_id);
CREATE INDEX IF NOT EXISTS idx_exercise_workout_workout_id ON exercise_workout (workout_id);
44 changes: 44 additions & 0 deletions internal/askar-postgres/model/exercise/create_exercise.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
package exercise

import (
"context"
"fmt"
"time"
"workout-training-api/internal/types/database"
)

func (m *ExerciseModel) CreateExercise(ctx context.Context, req database.CreateExerciseReq) (database.CreateExerciseResp, error) {

log := m.logger.With("exercise", "CreateExercise")

if req != nil {
log.ErrorContext(ctx, "req is nil")
return nil, fmt.Errorf("req is nil")
}

mdl := &Exercise{
Name: req.GetName(),
Description: req.GetDescription(),
MuscleGroups: req.GetMuscleGroups(),
Categories: req.GetCategories(),
}

query := `
INSERT INTO exercises (name, description, muscle_groups, categories)
VALUES ($1, $2, $3, $4)`

args := []interface{}{
mdl.Name, mdl.Description, mdl.MuscleGroups, mdl.Categories,
}

ctx, cancel := context.WithTimeout(ctx, 3*time.Second)
defer cancel()

_, err := m.db.ExecContext(ctx, query, args...)
if err != nil {
log.ErrorContext(ctx, "failed to execute query", "error", err)
return nil, fmt.Errorf("failed to execute query: %w", err)
}

return true, nil
}
44 changes: 44 additions & 0 deletions internal/askar-postgres/model/exercise/exercise.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
package exercise

import (
"strconv"
"time"
)

type Exercise struct {
ID int64
Name string
Description string
MuscleGroups []string
Categories []string
CreatedAt time.Time
UpdatedAt time.Time
}

func (e *Exercise) GetID() string {
return strconv.FormatInt(e.ID, 10)
}

func (e *Exercise) GetName() string {
return e.Name
}

func (e *Exercise) GetDescription() string {
return e.Description
}

func (e *Exercise) GetMuscleGroups() []string {
return e.MuscleGroups
}

func (e *Exercise) GetCategories() []string {
return e.Categories
}

func (e *Exercise) GetCreatedAt() time.Time {
return e.CreatedAt
}

func (e *Exercise) GetUpdatedAt() time.Time {
return e.UpdatedAt
}
17 changes: 17 additions & 0 deletions internal/askar-postgres/model/exercise/main.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
package exercise

import (
"database/sql"
"log/slog"
"workout-training-api/internal/config"
)

type ExerciseModel struct {
conf *config.PostgresConfig
logger *slog.Logger
db *sql.DB
}

func New(conf *config.PostgresConfig, logger *slog.Logger, db *sql.DB) *ExerciseModel {
return &ExerciseModel{conf: conf, logger: logger, db: db}
}
17 changes: 17 additions & 0 deletions internal/askar-postgres/model/main.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
package model

import (
"database/sql"
"log/slog"
"workout-training-api/internal/askar-postgres/model/exercise"
"workout-training-api/internal/config"
)

type Model struct {
*exercise.ExerciseModel
}

func New(conf *config.PostgresConfig, logger *slog.Logger, db *sql.DB) *Model {

return &Model{ExerciseModel: exercise.New(conf, logger.With(slog.String("component", "exercise")), db)}
}
2 changes: 1 addition & 1 deletion internal/config/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,9 +4,9 @@ import (
"context"
"flag"
"os"
"workout-training-api/internal/constant"

"github.com/joho/godotenv"
"github.com/talgat-ruby/lessons-go/projects/expense-tracker/internal/constant"
)

type Config struct {
Expand Down
30 changes: 25 additions & 5 deletions internal/config/postgres.go
Original file line number Diff line number Diff line change
Expand Up @@ -18,19 +18,39 @@ type PostgresConfig struct {
func newPostgresConfig(_ context.Context) *PostgresConfig {
port, _ := strconv.Atoi(os.Getenv("PG_PORT"))

// c := &PostgresConfig{
// Host: os.Getenv("PG_HOST"),
// Port: port,
// Name: os.Getenv("PG_NAME"),
// User: os.Getenv("PG_USER"),
// Password: os.Getenv("PG_PASSWORD"),
// }

// flag.StringVar(&c.Host, "pg-host", c.Host, "postgreSQL host [PG_HOST]")
// flag.IntVar(&c.Port, "pg-port", c.Port, "postgreSQL port [PG_PORT]")
// flag.StringVar(&c.Name, "pg-name", c.Name, "postgreSQL name [PG_NAME]")
// flag.StringVar(&c.User, "pg-user", c.User, "postgreSQL user [PG_USER]")
// flag.StringVar(&c.Password, "pg-password", c.Password, "postgreSQL password [PG_PASSWORD]")

c := &PostgresConfig{
Host: os.Getenv("PG_HOST"),
Host: "localhost",
Port: port,
Name: os.Getenv("PG_NAME"),
User: os.Getenv("PG_USER"),
Password: os.Getenv("PG_PASSWORD"),
Name: "postgres",
User: "postgres",
Password: "postgres",
}

flag.StringVar(&c.Host, "pg-host", c.Host, "postgreSQL host [PG_HOST]")
// postgres://workoutdb:admin@localhost/workoutdb?sslmode=disable
// postgres://postgres:admin@localhost/workoutdb
// postgres://postgres:admin@localhost/workoutdb?sslmode=disable

flag.StringVar(&c.Host, "localhost", c.Host, "postgreSQL host [PG_HOST]")
flag.IntVar(&c.Port, "pg-port", c.Port, "postgreSQL port [PG_PORT]")
flag.StringVar(&c.Name, "pg-name", c.Name, "postgreSQL name [PG_NAME]")
flag.StringVar(&c.User, "pg-user", c.User, "postgreSQL user [PG_USER]")
flag.StringVar(&c.Password, "pg-password", c.Password, "postgreSQL password [PG_PASSWORD]")

flag.Parse()

return c
}
10 changes: 10 additions & 0 deletions internal/constant/env.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
package constant

type Environment string

const (
EnvironmentLocal Environment = "LOCAL"
EnvironmentTest Environment = "TEST"
EnvironmentDev Environment = "DEV"
EnvironmentProd Environment = "PROD"
)