-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Showing
9 changed files
with
270 additions
and
2 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,66 @@ | ||
package db | ||
|
||
import ( | ||
"context" | ||
|
||
"github.com/jackc/pgconn" | ||
"github.com/jackc/pgx/v4" | ||
) | ||
|
||
// Handler - функция, которая выполняется в транзакции | ||
type Handler func(ctx context.Context) error | ||
|
||
// Client клиент для работы с БД | ||
type Client interface { | ||
DB() DB | ||
Close() error | ||
} | ||
|
||
// TxManager менеджер транзакций, который выполняет указанный пользователем обработчик в транзакции | ||
type TxManager interface { | ||
ReadCommitted(ctx context.Context, f Handler) error | ||
} | ||
|
||
// Query обертка над запросом, хранящая имя запроса и сам запрос | ||
// Имя запроса используется для логирования и потенциально может использоваться еще где-то, например, для трейсинга | ||
type Query struct { | ||
Name string | ||
QueryRaw string | ||
} | ||
|
||
// Transactor интерфейс для работы с транзакциями | ||
type Transactor interface { | ||
BeginTx(ctx context.Context, txOptions pgx.TxOptions) (pgx.Tx, error) | ||
} | ||
|
||
// SQLExecer комбинирует NamedExecer и QueryExecer | ||
type SQLExecer interface { | ||
NamedExecer | ||
QueryExecer | ||
} | ||
|
||
// NamedExecer интерфейс для работы с именованными запросами с помощью тегов в структурах | ||
type NamedExecer interface { | ||
ScanOneContext(ctx context.Context, dest interface{}, q Query, args ...interface{}) error | ||
ScanAllContext(ctx context.Context, dest interface{}, q Query, args ...interface{}) error | ||
} | ||
|
||
// QueryExecer интерфейс для работы с обычными запросами | ||
type QueryExecer interface { | ||
ExecContext(ctx context.Context, q Query, args ...interface{}) (pgconn.CommandTag, error) | ||
QueryContext(ctx context.Context, q Query, args ...interface{}) (pgx.Rows, error) | ||
QueryRowContext(ctx context.Context, q Query, args ...interface{}) pgx.Row | ||
} | ||
|
||
// Pinger интерфейс для проверки соединения с БД | ||
type Pinger interface { | ||
Ping(ctx context.Context) error | ||
} | ||
|
||
// DB интерфейс для работы с БД | ||
type DB interface { | ||
SQLExecer | ||
Transactor | ||
Pinger | ||
Close() | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,21 @@ | ||
package model | ||
|
||
import ( | ||
"database/sql" | ||
"time" | ||
) | ||
|
||
type User struct { | ||
ID int64 | ||
Info UserInfo | ||
CreatedAt time.Time | ||
UpdatedAt sql.NullTime | ||
} | ||
|
||
type UserInfo struct { | ||
Name string | ||
Email string | ||
Password string | ||
PasswordConfirm string | ||
Role string // todo: enum | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,15 @@ | ||
package repository | ||
|
||
import ( | ||
"context" | ||
|
||
"github.com/artemzi/auth/internal/model" | ||
) | ||
|
||
type UserRepository interface { | ||
Create(ctx context.Context, info *model.UserInfo) (int64, error) | ||
Get(ctx context.Context, id int64) (*model.User, error) | ||
// TODO: implement it | ||
// Update(ctx context.Context, info *model.User) error | ||
// Delete(ctx context.Context, id int64) error | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,21 @@ | ||
package entity | ||
|
||
import ( | ||
"database/sql" | ||
"time" | ||
) | ||
|
||
type User struct { | ||
ID int64 | ||
Info UserInfo | ||
CreatedAt time.Time | ||
UpdatedAt sql.NullTime | ||
} | ||
|
||
type UserInfo struct { | ||
Name string | ||
Email string | ||
Passowrd string | ||
PasswordConfirm string | ||
Role string // todo: enum | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,25 @@ | ||
package mapper | ||
|
||
import ( | ||
"github.com/artemzi/auth/internal/model" | ||
entity "github.com/artemzi/auth/internal/repository/user/entity" | ||
) | ||
|
||
func ToUserFromEntity(user *entity.User) *model.User { | ||
return &model.User{ | ||
ID: user.ID, | ||
Info: ToUserInfoFromEntity(user.Info), | ||
CreatedAt: user.CreatedAt, | ||
UpdatedAt: user.UpdatedAt, | ||
} | ||
} | ||
|
||
func ToUserInfoFromEntity(info entity.UserInfo) model.UserInfo { | ||
return model.UserInfo{ | ||
Name: info.Name, | ||
Email: info.Email, | ||
Password: info.Passowrd, | ||
PasswordConfirm: info.PasswordConfirm, | ||
Role: info.Role, | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,111 @@ | ||
package user | ||
|
||
import ( | ||
"context" | ||
|
||
sq "github.com/Masterminds/squirrel" | ||
"github.com/artemzi/auth/internal/client/db" | ||
"github.com/artemzi/auth/internal/model" | ||
"github.com/artemzi/auth/internal/repository" | ||
entity "github.com/artemzi/auth/internal/repository/user/entity" | ||
"github.com/artemzi/auth/internal/repository/user/mapper" | ||
"github.com/fatih/color" | ||
log "github.com/sirupsen/logrus" | ||
) | ||
|
||
const ( | ||
tableName = "user" | ||
|
||
idColumn = "id" | ||
nameColumn = "name" | ||
emailColumn = "email" | ||
passwordColumn = "password" | ||
passwordConfirmColumn = "password_confirm" | ||
roleColumn = "role" | ||
createdAtColumn = "created_at" | ||
updatedAtColumn = "updated_at" | ||
) | ||
|
||
type repo struct { | ||
db db.Client | ||
} | ||
|
||
func NewRepository(db db.Client) repository.UserRepository { | ||
return &repo{db: db} | ||
} | ||
|
||
func (r *repo) Create(ctx context.Context, info *model.UserInfo) (int64, error) { | ||
builder := sq.Insert(tableName). | ||
PlaceholderFormat(sq.Dollar). | ||
Columns(nameColumn, emailColumn, passwordColumn, passwordConfirmColumn, roleColumn). | ||
Values(info.Name, info.Email, info.Password, info.PasswordConfirm, info.Role). | ||
Suffix("RETURNING id") | ||
|
||
query, args, err := builder.ToSql() | ||
if err != nil { | ||
return 0, err | ||
} | ||
|
||
q := db.Query{ | ||
Name: "user_repository.Create", | ||
QueryRaw: query, | ||
} | ||
|
||
var userID int64 | ||
err = r.db.DB().QueryRowContext(ctx, q, args...).Scan(&userID) | ||
if err != nil { | ||
log.Errorf("failed to INSERT user: %v", err) | ||
return 0, err | ||
} | ||
|
||
log.WithContext(ctx).Infof("inserted user with id: %d", userID) | ||
return userID, nil | ||
} | ||
|
||
func (r *repo) Get(ctx context.Context, id int64) (*model.User, error) { | ||
query := "SELECT id, name, email, role, created_at, updated_at FROM \"user\" WHERE id = $1;" | ||
|
||
q := db.Query{ | ||
Name: "user_repository.Get", | ||
QueryRaw: query, | ||
} | ||
|
||
var user entity.User | ||
err := r.db.DB().QueryRowContext(ctx, q, id). | ||
Scan(&user.ID, &user.Info.Name, &user.Info.Email, &user.Info.Role, &user.CreatedAt, &user.UpdatedAt) | ||
if err != nil { | ||
log.Errorf("failed to GET user: %v", err) | ||
return nil, err | ||
} | ||
|
||
log.WithContext(ctx).Info(color.GreenString("Got User id: "), id) | ||
return mapper.ToUserFromEntity(&user), nil | ||
} | ||
|
||
// func (s *repo) Update(ctx context.Context, req *desc.UpdateRequest) (*emptypb.Empty, error) { | ||
// query := "UPDATE \"user\" SET name = $1, email = $2 WHERE id = $3;" | ||
|
||
// _, err := s.pool.Exec(ctx, query, req.GetInfo().GetName().Value, req.GetInfo().GetEmail().Value, req.GetId()) | ||
// if err != nil { | ||
// log.Errorf("failed to UPDATE user: %v", err) | ||
// return nil, err | ||
// } | ||
|
||
// log.WithContext(ctx).Info(color.GreenString("Updated User id: "), req.GetId()) | ||
// out := new(emptypb.Empty) | ||
|
||
// return out, nil | ||
// } | ||
|
||
// func (r *repo) Delete(ctx context.Context, id int64) error { | ||
// query := "DELETE FROM \"user\" WHERE id = $1;" | ||
|
||
// _, err := r.db.DB().pool.Exec(ctx, query, id) | ||
// if err != nil { | ||
// log.Errorf("failed to DELETE user: %v", err) | ||
// return err | ||
// } | ||
|
||
// log.WithContext(ctx).Info(color.GreenString("Deleted User id: "), id) | ||
// return nil | ||
// } |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters