99 lines
2.5 KiB
Go
99 lines
2.5 KiB
Go
package postgres
|
|
|
|
import (
|
|
"context"
|
|
"github.com/jackc/pgx/v4"
|
|
"serverctl/pkg/application/projects"
|
|
"serverctl/pkg/db"
|
|
)
|
|
|
|
var _ projects.Repository = &ProjectsRepository{}
|
|
|
|
type ProjectsRepository struct {
|
|
db *db.Client
|
|
}
|
|
|
|
func NewProjectsRepository(db *db.Client) projects.Repository {
|
|
return &ProjectsRepository{db: db}
|
|
}
|
|
|
|
type projectData struct {
|
|
ProjectId int
|
|
ProjectName string
|
|
MemberId int
|
|
MemberRole string
|
|
}
|
|
|
|
func (p ProjectsRepository) Create(ctx context.Context, project *projects.CreateProject) (int, error) {
|
|
conn := p.db.GetConn(ctx)
|
|
defer conn.Release()
|
|
|
|
var projectId int
|
|
err := conn.BeginTxFunc(ctx, pgx.TxOptions{}, func(tx pgx.Tx) error {
|
|
err := tx.QueryRow(ctx, "insert into sctl_project(name) values ($1) returning id", project.Name).Scan(&projectId)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
|
|
_, err = tx.Exec(ctx, "insert into sctl_project_member(project_id, member_id, role) values($1, $2, $3)", projectId, project.MemberIds[0], "admin")
|
|
return err
|
|
})
|
|
if err != nil {
|
|
return -1, err
|
|
}
|
|
|
|
return projectId, nil
|
|
}
|
|
|
|
func (p ProjectsRepository) GetForMemberId(ctx context.Context, memberId int) ([]*projects.Project, error) {
|
|
conn := p.db.GetConn(ctx)
|
|
defer conn.Release()
|
|
|
|
rows, _ := conn.Query(ctx, `
|
|
select pm.project_id, name project_name, pm.member_id, pm.role member_role
|
|
from sctl_project
|
|
join sctl_project_member pm
|
|
on sctl_project.id = pm.project_id
|
|
join sctl_user u
|
|
on pm.member_id = u.id
|
|
where pm.member_id = $1
|
|
order by pm.project_id
|
|
`, memberId)
|
|
projectsDataArr := make([]*projectData, 0)
|
|
for rows.Next() {
|
|
var pd projectData
|
|
err := rows.Scan(&pd.ProjectId, &pd.ProjectName, &pd.MemberId, &pd.MemberRole)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
projectsDataArr = append(projectsDataArr, &pd)
|
|
}
|
|
|
|
projectsArr := make([]*projects.Project, 0)
|
|
var tempProject *projects.Project
|
|
for _, project := range projectsDataArr {
|
|
if tempProject == nil {
|
|
tempProject = projects.NewProject(
|
|
project.ProjectId,
|
|
project.ProjectName,
|
|
projects.NewProjectMember(project.MemberId, project.MemberRole),
|
|
)
|
|
} else if tempProject.Id != project.ProjectId {
|
|
projectsArr = append(projectsArr, tempProject)
|
|
tempProject = projects.NewProject(
|
|
project.ProjectId,
|
|
project.ProjectName,
|
|
projects.NewProjectMember(project.MemberId, project.MemberRole),
|
|
)
|
|
} else {
|
|
tempProject.AddMember(
|
|
projects.NewProjectMember(project.MemberId, project.MemberRole))
|
|
}
|
|
}
|
|
if tempProject != nil {
|
|
projectsArr = append(projectsArr, tempProject)
|
|
}
|
|
|
|
return projectsArr, nil
|
|
}
|