package postgres import ( "context" "errors" "fmt" "git.dragse.it/anthrove/otter-space-sdk/pkg/models" log "github.com/sirupsen/logrus" "gorm.io/gorm" ) func CreateAnthrovePostNode(ctx context.Context, db *gorm.DB, anthrovePost *models.Post) error { post := models.Post{ BaseModel: models.BaseModel{ ID: string(anthrovePost.ID), }, Rating: anthrovePost.Rating, } err := db.WithContext(ctx).Create(&post).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 string) (*models.Post, error) { if anthrovePostID == "" { return false, fmt.Errorf("anthrovePostID is required") } return executeCheckQuery(ctx, db, "id = ?", string(anthrovePostID)) } func GetPostBySourceURL(ctx context.Context, db *gorm.DB, sourceURL string) (*models.Post, bool, 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, false, nil } return nil, false, err } var post models.Post err = db.WithContext(ctx).First(&post, "id = ?", postRef.PostID).Error if err != nil { return nil, false, err } pgPost := graphModels.AnthrovePost{ PostID: models.AnthrovePostID(post.ID), Rating: post.Rating, } //TODO Now test it! :D // Naaa // D: return &pgPost, true, nil } func GetPostBySourceID(ctx context.Context, db *gorm.DB, sourceID string) (*models.Post, error) { return executeCheckQuery(ctx, db, "source_id = ?", sourceID) } func executeCheckQuery(ctx context.Context, db *gorm.DB, query string, args ...interface{}) (bool, error) { var count int64 err := db.WithContext(ctx).Model(&models.Post{}).Where(query, args...).Count(&count).Error if err != nil { return false, err } exists := count > 0 log.WithFields(log.Fields{ "query": query, "args": args, "exists": exists, }).Trace("database: executed check query") return exists, nil }