74 lines
1.9 KiB
Go
74 lines
1.9 KiB
Go
package postgres
|
|
|
|
import (
|
|
"context"
|
|
"fmt"
|
|
"git.dragse.it/anthrove/otter-space-sdk/pkg/models"
|
|
"git.dragse.it/anthrove/otter-space-sdk/pkg/models/pgModels"
|
|
log "github.com/sirupsen/logrus"
|
|
"gorm.io/gorm"
|
|
)
|
|
|
|
func CreateAnthrovePostNode(ctx context.Context, db *gorm.DB, anthrovePostID models.AnthrovePostID, anthroveRating models.Rating) error {
|
|
post := pgModels.Post{
|
|
BaseModel: pgModels.BaseModel{
|
|
ID: string(anthrovePostID),
|
|
},
|
|
Rating: anthroveRating,
|
|
}
|
|
|
|
err := db.WithContext(ctx).Create(&post).Error
|
|
if err != nil {
|
|
return err
|
|
}
|
|
|
|
log.WithFields(log.Fields{
|
|
"anthrove_post_id": anthrovePostID,
|
|
"anthrove_post_rating": anthroveRating,
|
|
}).Trace("database: created anthrove post")
|
|
|
|
return nil
|
|
}
|
|
|
|
func CheckIfAnthrovePostNodeExistsByAnthroveID(ctx context.Context, db *gorm.DB, anthrovePostID models.AnthrovePostID) (bool, error) {
|
|
if anthrovePostID == "" {
|
|
return false, fmt.Errorf("anthrovePostID is required")
|
|
}
|
|
|
|
return executeCheckQuery(ctx, db, "id = ?", string(anthrovePostID))
|
|
}
|
|
|
|
func CheckIfAnthrovePostNodeExistsBySourceURL(ctx context.Context, db *gorm.DB, sourceURL string) (bool, error) {
|
|
var size int64
|
|
err := db.WithContext(ctx).Model(&pgModels.PostReference{}).Where("url = ?", sourceURL).Count(&size).Error
|
|
|
|
if err != nil {
|
|
return false, err
|
|
}
|
|
|
|
return size > 0, nil
|
|
}
|
|
|
|
func CheckIfAnthrovePostNodeExistsBySourceID(ctx context.Context, db *gorm.DB, sourceID string) (bool, 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(&pgModels.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
|
|
}
|