package repositories import ( "context" "database/sql" "github.com/dmitriygnatenko/internal/interfaces" "github.com/dmitriygnatenko/internal/models" ) type articleRepository struct { db *sql.DB } func InitArticleRepository(db *sql.DB) interfaces.IArticleRepository { return articleRepository{db: db} } func (a articleRepository) GetAllPreview(ctx context.Context) ([]models.ArticlePreview, error) { var res []models.ArticlePreview query := "SELECT id, url, publish_time, title, preview_text, image " + "FROM " + articleTableName + " " + "WHERE is_active = 1 " + "ORDER BY publish_time DESC" rows, err := a.db.QueryContext(ctx, query) if err != nil { return nil, err } defer rows.Close() for rows.Next() { row := models.ArticlePreview{} err = rows.Scan( &row.ID, &row.URL, &row.PublishTime, &row.Title, &row.PreviewText, &row.Image, ) if err != nil { return nil, err } res = append(res, row) } if err = rows.Err(); err != nil { return nil, err } return res, nil } func (a articleRepository) GetPreviewByTagID(ctx context.Context, tagID int) ([]models.ArticlePreview, error) { var res []models.ArticlePreview query := "SELECT a.id, a.url, a.publish_time, a.title, a.preview_text, a.image " + "FROM " + articleTableName + " a, " + articleTagTableName + " at " + "WHERE a.is_active = 1 AND at.article_id = a.id AND at.tag_id = ? " + "ORDER BY a.publish_time DESC" rows, err := a.db.QueryContext(ctx, query, tagID) if err != nil { return nil, err } defer rows.Close() for rows.Next() { row := models.ArticlePreview{} err = rows.Scan( &row.ID, &row.URL, &row.PublishTime, &row.Title, &row.PreviewText, &row.Image, ) if err != nil { return nil, err } res = append(res, row) } if err = rows.Err(); err != nil { return nil, err } return res, nil } func (a articleRepository) GetByURL(ctx context.Context, url string) (*models.Article, error) { var res models.Article query := "SELECT id, url, publish_time, title, image, text, preview_text, meta_keywords, meta_desc, is_active " + "FROM " + articleTableName + " " + "WHERE url = ? LIMIT 1" err := a.db.QueryRowContext(ctx, query, url). Scan(&res.ID, &res.URL, &res.PublishTime, &res.Title, &res.Image, &res.Text, &res.PreviewText, &res.MetaKeywords, &res.MetaDescription, &res.IsActive) if err != nil { return nil, err } return &res, nil } func (a articleRepository) GetByID(ctx context.Context, ID int) (*models.Article, error) { var res models.Article query := "SELECT id, url, publish_time, title, image, text, preview_text, meta_keywords, meta_desc, is_active " + "FROM " + articleTableName + " " + "WHERE id = ? LIMIT 1" err := a.db.QueryRowContext(ctx, query, ID). Scan(&res.ID, &res.URL, &res.PublishTime, &res.Title, &res.Image, &res.Text, &res.PreviewText, &res.MetaKeywords, &res.MetaDescription, &res.IsActive) if err != nil { return nil, err } return &res, nil }