micrach/repositories/files_repository.go

101 lines
1.8 KiB
Go
Raw Permalink Normal View History

2021-09-01 18:40:13 +03:00
package repositories
import (
"context"
Db "micrach/db"
2021-09-01 23:00:37 +03:00
"github.com/jackc/pgx/v5"
2021-09-01 18:40:13 +03:00
)
type FilesRepository struct{}
var Files FilesRepository
func toInt32s(values []int) []int32 {
if values == nil {
return nil
}
result := make([]int32, len(values))
for i, value := range values {
result[i] = int32(value)
}
return result
}
func (r *FilesRepository) Create(ctx context.Context, f File) error {
2021-09-01 18:40:13 +03:00
sql := `
INSERT INTO files (post_id, name, ext, size)
VALUES ($1, $2, $3, $4)
`
row := Db.Pool.QueryRow(
ctx, sql, f.PostID, f.Name, f.Ext, f.Size,
2021-09-01 18:40:13 +03:00
)
err := row.Scan()
2021-09-03 02:34:45 +03:00
if err != nil && err != pgx.ErrNoRows {
return err
}
2021-09-01 18:40:13 +03:00
return nil
}
2021-09-01 23:00:37 +03:00
func (r *FilesRepository) GetByPostIDs(ctx context.Context, postIDs []int) (map[int][]File, error) {
2021-09-01 23:00:37 +03:00
sql := `
2021-09-11 16:05:31 +03:00
SELECT id, post_id, name, size, ext
2021-09-01 23:00:37 +03:00
FROM files
WHERE post_id = ANY ($1)
ORDER BY id ASC
`
rows, err := Db.Pool.Query(ctx, sql, toInt32s(postIDs))
2021-09-01 23:00:37 +03:00
if err != nil {
return nil, err
}
defer rows.Close()
2021-09-01 23:00:37 +03:00
filesMapByPostId := make(map[int][]File)
for rows.Next() {
var file File
2021-09-11 16:05:31 +03:00
err = rows.Scan(&file.ID, &file.PostID, &file.Name, &file.Size, &file.Ext)
2021-09-01 23:00:37 +03:00
if err != nil {
return nil, err
}
if filesMapByPostId[file.PostID] == nil {
filesMapByPostId[file.PostID] = []File{}
}
filesMapByPostId[file.PostID] = append(
filesMapByPostId[file.PostID],
file,
)
}
if err := rows.Err(); err != nil {
return nil, err
}
2021-09-01 23:00:37 +03:00
return filesMapByPostId, nil
}
2021-09-10 19:16:53 +03:00
func (r *FilesRepository) CreateInTx(ctx context.Context, tx pgx.Tx, f File) (int, error) {
2021-09-10 19:16:53 +03:00
sql := `
INSERT INTO files (post_id, name, ext, size)
VALUES ($1, $2, $3, $4)
2021-09-11 16:05:31 +03:00
RETURNING id
2021-09-10 19:16:53 +03:00
`
row := tx.QueryRow(
ctx, sql, f.PostID, f.Name, f.Ext, f.Size,
2021-09-10 19:16:53 +03:00
)
2021-09-11 16:05:31 +03:00
createdFile := new(File)
err := row.Scan(&createdFile.ID)
2021-09-10 19:16:53 +03:00
if err != nil && err != pgx.ErrNoRows {
2021-09-11 16:05:31 +03:00
return 0, err
2021-09-10 19:16:53 +03:00
}
2021-09-11 16:05:31 +03:00
return createdFile.ID, nil
2021-09-10 19:16:53 +03:00
}