clients.go 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. package dbstore
  2. import (
  3. "context"
  4. "fmt"
  5. "git.linuxforward.com/byop/byop-engine/models"
  6. "gorm.io/gorm"
  7. )
  8. // CreateClient creates a new client using GORM
  9. func (s *SQLiteStore) CreateClient(ctx context.Context, client *models.Client) error {
  10. result := s.db.WithContext(ctx).Create(client)
  11. if result.Error != nil {
  12. return fmt.Errorf("failed to create client: %w", result.Error)
  13. }
  14. return nil
  15. }
  16. // GetAllClients retrieves all clients using GORM
  17. func (s *SQLiteStore) GetAllClients(ctx context.Context) ([]*models.Client, error) {
  18. var clients []*models.Client
  19. result := s.db.WithContext(ctx).Find(&clients)
  20. if result.Error != nil {
  21. return nil, fmt.Errorf("failed to get all clients: %w", result.Error)
  22. }
  23. return clients, nil
  24. }
  25. // GetClientByID retrieves a client by ID using GORM
  26. func (s *SQLiteStore) GetClientByID(ctx context.Context, id uint) (*models.Client, error) {
  27. var client models.Client
  28. result := s.db.WithContext(ctx).First(&client, id)
  29. if result.Error != nil {
  30. if result.Error == gorm.ErrRecordNotFound {
  31. return nil, models.NewErrNotFound(fmt.Sprintf("client with ID %d not found", id), result.Error)
  32. }
  33. return nil, fmt.Errorf("failed to get client by ID: %w", result.Error)
  34. }
  35. return &client, nil
  36. }
  37. // UpdateClient updates an existing client using GORM
  38. func (s *SQLiteStore) UpdateClient(ctx context.Context, client *models.Client) error {
  39. result := s.db.WithContext(ctx).Save(client)
  40. if result.Error != nil {
  41. return fmt.Errorf("failed to update client: %w", result.Error)
  42. }
  43. if result.RowsAffected == 0 {
  44. return models.NewErrNotFound(fmt.Sprintf("client with ID %d not found for update", client.ID), nil)
  45. }
  46. return nil
  47. }
  48. // DeleteClient deletes a client by ID using GORM
  49. func (s *SQLiteStore) DeleteClient(ctx context.Context, id uint) error {
  50. result := s.db.WithContext(ctx).Delete(&models.Client{}, id)
  51. if result.Error != nil {
  52. return fmt.Errorf("failed to delete client: %w", result.Error)
  53. }
  54. if result.RowsAffected == 0 {
  55. return models.NewErrNotFound(fmt.Sprintf("client with ID %d not found for deletion", id), nil)
  56. }
  57. return nil
  58. }