package tag import ( "context" "log/slog" "spend-sparrow/internal/core" "github.com/google/uuid" "github.com/jmoiron/sqlx" ) type Db interface { insert(ctx context.Context, tag Tag) (*Tag, error) update(ctx context.Context, tag Tag) (*Tag, error) delete(ctx context.Context, userId uuid.UUID, id uuid.UUID) error get(ctx context.Context, userId uuid.UUID, id uuid.UUID) (*Tag, error) getAll(ctx context.Context, userId uuid.UUID) ([]Tag, error) } type DbSqlite struct { db *sqlx.DB } func NewDbSqlite(db *sqlx.DB) *DbSqlite { return &DbSqlite{db: db} } func (db DbSqlite) insert(ctx context.Context, tag Tag) (*Tag, error) { r, err := db.db.ExecContext(ctx, ` INSERT INTO tag (id, user_id, name, created_at, created_by, updated_at, updated_by) VALUES (?, ?, ?, ?, ?, ?, ?)`, tag.Id, tag.UserId, tag.Name, tag.CreatedAt, tag.CreatedBy, tag.UpdatedAt, tag.UpdatedBy, ) err = core.TransformAndLogDbError(ctx, "tag", r, err) if err != nil { return nil, core.ErrInternal } return db.get(ctx, tag.UserId, tag.Id) } func (db DbSqlite) update(ctx context.Context, tag Tag) (*Tag, error) { _, err := db.db.ExecContext(ctx, ` UPDATE tag SET name = ?, updated_at = ?, updated_by = ? WHERE user_id = ? AND id = ?`, tag.Name, tag.UpdatedAt, tag.UpdatedBy, tag.UserId, tag.Id) if err != nil { slog.ErrorContext(ctx, "SQL error UpdateUser", "err", err) return nil, core.ErrInternal } return db.get(ctx, tag.UserId, tag.Id) } func (db DbSqlite) delete(ctx context.Context, userId uuid.UUID, id uuid.UUID) error { r, err := db.db.ExecContext( ctx, "DELETE FROM tag WHERE user_id = ? AND id = ?", userId, id) err = core.TransformAndLogDbError(ctx, "tag", r, err) if err != nil { return err } return nil } func (db DbSqlite) get(ctx context.Context, userId uuid.UUID, id uuid.UUID) (*Tag, error) { var tag Tag err := db.db.Get(&tag, "SELECT * FROM tag WHERE id = ? AND user_id = ?", id, userId) if err != nil { slog.ErrorContext(ctx, "Could not get tag", "err", err) return nil, core.ErrInternal } return &tag, nil } func (db DbSqlite) getAll(ctx context.Context, userId uuid.UUID) ([]Tag, error) { var tags []Tag err := db.db.Select(&tags, "SELECT * FROM tag WHERE user_id = ?", userId) if err != nil { slog.ErrorContext(ctx, "Could not GetAll tag", "err", err) return nil, core.ErrInternal } return tags, nil }