package postgres import ( "context" "errors" "fmt" "git.dragse.it/anthrove/otter-space-sdk/pkg/models" log "github.com/sirupsen/logrus" "gorm.io/gorm" ) func CreatePost(ctx context.Context, db *gorm.DB, anthrovePost *models.Post) error { err := db.WithContext(ctx).Create(&anthrovePost).Error if err != nil { return err } log.WithFields(log.Fields{ "anthrove_post_id": anthrovePost.ID, "anthrove_post_rating": anthrovePost.Rating, }).Trace("database: created anthrove post") return nil } func GetPostByAnthroveID(ctx context.Context, db *gorm.DB, anthrovePostID models.AnthrovePostID) (*models.Post, error) { if anthrovePostID == "" { return nil, fmt.Errorf("anthrovePostID is required") } var post models.Post err := db.WithContext(ctx).First(&post, "id = ?", anthrovePostID).Error if err != nil { return nil, err } return &post, nil } func GetPostByURL(ctx context.Context, db *gorm.DB, sourceURL string) (*models.Post, error) { var post models.Post err := db.WithContext(ctx).Raw(`SELECT p.id AS id, p.rating as rating FROM "Post" AS p INNER JOIN "PostReference" AS pr ON p.id = pr.post_id AND pr.url = $1 LIMIT 1`, sourceURL).First(&post).Error if err != nil { if errors.Is(err, gorm.ErrRecordNotFound) { return nil, nil } return nil, err } return &post, nil } func GetPostBySourceID(ctx context.Context, db *gorm.DB, sourceID models.AnthroveSourceID) (*models.Post, error) { var post models.Post err := db.WithContext(ctx).Raw(`SELECT p.id AS id, p.rating as rating FROM "Post" AS p INNER JOIN "PostReference" AS pr ON p.id = pr.post_id AND pr.source_id = $1 LIMIT 1`, sourceID).First(&post).Error if err != nil { if errors.Is(err, gorm.ErrRecordNotFound) { return nil, nil } return nil, err } return &post, nil }