46 lines
1.3 KiB
Go
46 lines
1.3 KiB
Go
package database
|
|
|
|
import (
|
|
"context"
|
|
"fmt"
|
|
|
|
"github.com/jackc/pgx/v5/pgtype"
|
|
|
|
"github.com/TelegramExchange/pkg/transaction"
|
|
"github.com/TelegramExchange/tgex-backend/tg_parser/internal/domain"
|
|
)
|
|
|
|
func (d *Database) CreatePost(ctx context.Context, post domain.Post) error {
|
|
query := `INSERT INTO post (id, channel_id, message_id, text, published_at)
|
|
VALUES ($1, $2, $3, $4, $5)
|
|
ON CONFLICT (channel_id, message_id) DO UPDATE
|
|
SET text = EXCLUDED.text,
|
|
published_at = COALESCE(post.published_at, EXCLUDED.published_at),
|
|
updated_at = CURRENT_TIMESTAMP;`
|
|
|
|
txOrPool := transaction.TryExtractTX(ctx)
|
|
|
|
dto := createPostDTO{
|
|
ID: pgtype.UUID{Bytes: post.ID, Valid: true},
|
|
ChannelID: pgtype.UUID{Bytes: post.ChannelID, Valid: true},
|
|
MessageID: pgtype.Int4{Int32: int32(post.MessageID), Valid: true},
|
|
Text: pgtype.Text{String: post.Text, Valid: true},
|
|
PublishedAt: pgtype.Timestamptz{Time: post.PublishedAt, Valid: !post.PublishedAt.IsZero()},
|
|
}
|
|
|
|
_, err := txOrPool.Exec(ctx, query, dto.ID, dto.ChannelID, dto.MessageID, dto.Text, dto.PublishedAt)
|
|
if err != nil {
|
|
return fmt.Errorf("txOrPool.Exec: %w", err)
|
|
}
|
|
|
|
return nil
|
|
}
|
|
|
|
type createPostDTO struct {
|
|
ID pgtype.UUID
|
|
ChannelID pgtype.UUID
|
|
MessageID pgtype.Int4
|
|
Text pgtype.Text
|
|
PublishedAt pgtype.Timestamptz
|
|
}
|