package repository import ( "context" "database/sql" "errors" "fmt" "time" "git.jamestombleson.com/jtom38/newsbot-api/internal/entity" "github.com/huandu/go-sqlbuilder" ) type UserSourceRepo interface { Create(ctx context.Context, userId, sourceId int64) (int64, error) SoftDelete(ctx context.Context, id int64) (int64, error) Restore(ctx context.Context, id int64) (int64, error) Delete(ctx context.Context, id int64) (int64, error) ListByUser(ctx context.Context, page, limit int, userId int64) ([]entity.UserSourceSubscriptionEntity, error) } type userSourceRepository struct { conn *sql.DB defaultLimit int defaultOffset int } func NewUserSourceRepository(conn *sql.DB) userSourceRepository { return userSourceRepository{ conn: conn, defaultLimit: 50, defaultOffset: 50, } } func (r userSourceRepository) Create(ctx context.Context, userId, sourceId int64) (int64, error) { dt := time.Now() queryBuilder := sqlbuilder.NewInsertBuilder() queryBuilder.InsertInto("UserSourceSubscriptions") queryBuilder.Cols("UpdatedAt", "CreatedAt", "DeletedAt", "UserID", "SourceID") queryBuilder.Values(dt, dt, timeZero, userId, sourceId) query, args := queryBuilder.Build() _, err := r.conn.ExecContext(ctx, query, args...) if err != nil { return 0, err } return 1, nil } func (r userSourceRepository) SoftDelete(ctx context.Context, id int64) (int64, error) { return softDeleteRow(ctx, r.conn, "UserSourceSubscriptions", id) } func (r userSourceRepository) Restore(ctx context.Context, id int64) (int64, error) { return restoreRow(ctx, r.conn, "UserSourceSubscriptions", id) } func (r userSourceRepository) Delete(ctx context.Context, id int64) (int64, error) { return deleteFromTable(ctx, r.conn, "UserSourceSubscriptions", id) } func (r userSourceRepository) ListByUser(ctx context.Context, page, limit int, userId int64) ([]entity.UserSourceSubscriptionEntity, error) { builder := sqlbuilder.NewSelectBuilder() builder.Select("*") builder.From("UserSourceSubscriptions") builder.Where( builder.Equal("UserID", userId), ) builder.Offset(page * limit) builder.Limit(limit) query, args := builder.Build() rows, err := r.conn.QueryContext(ctx, query, args...) if err != nil { return []entity.UserSourceSubscriptionEntity{}, err } data := r.processRows(rows) if len(data) == 0 { return []entity.UserSourceSubscriptionEntity{}, errors.New(ErrUserNotFound) } return data, nil } func (ur userSourceRepository) processRows(rows *sql.Rows) []entity.UserSourceSubscriptionEntity { items := []entity.UserSourceSubscriptionEntity{} for rows.Next() { var id int64 var createdAt time.Time var updatedAt time.Time var deletedAt time.Time var userId int64 var sourceId int64 err := rows.Scan( &id, &createdAt, &updatedAt, &deletedAt, &userId, &sourceId, ) if err != nil { fmt.Println(err) } item := entity.UserSourceSubscriptionEntity{ ID: id, CreatedAt: createdAt, UpdatedAt: updatedAt, DeletedAt: deletedAt, UserID: userId, SourceID: sourceId, } items = append(items, item) } return items }