client.go 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. package dbstore
  2. import (
  3. "fmt"
  4. "git.linuxforward.com/byop/byop-engine/dbmanager"
  5. "git.linuxforward.com/byop/byop-engine/models"
  6. "github.com/google/uuid"
  7. "gorm.io/gorm"
  8. )
  9. // ClientStore handles database operations for clients
  10. type ClientStore struct {
  11. db *gorm.DB
  12. }
  13. // NewClientStore creates a new ClientStore
  14. func NewClientStore(dbManager dbmanager.DbManager) *ClientStore {
  15. return &ClientStore{
  16. db: dbManager.GetDB(),
  17. }
  18. }
  19. // Create creates a new client
  20. func (cs *ClientStore) Create(client *models.Client) error {
  21. // Generate ID if not provided
  22. if client.ID == "" {
  23. client.ID = uuid.New().String()
  24. }
  25. // GORM will handle created_at and updated_at automatically
  26. return cs.db.Create(client).Error
  27. }
  28. // GetByID retrieves a client by ID
  29. func (cs *ClientStore) GetByID(id string) (*models.Client, error) {
  30. var client models.Client
  31. result := cs.db.First(&client, "id = ?", id)
  32. if result.Error != nil {
  33. if result.Error == gorm.ErrRecordNotFound {
  34. return nil, nil // No client found
  35. }
  36. return nil, fmt.Errorf("failed to get client: %w", result.Error)
  37. }
  38. return &client, nil
  39. }
  40. // Update updates an existing client
  41. func (cs *ClientStore) Update(client *models.Client) error {
  42. return cs.db.Save(client).Error
  43. }
  44. // Delete deletes a client by ID
  45. func (cs *ClientStore) Delete(id string) error {
  46. return cs.db.Delete(&models.Client{}, "id = ?", id).Error
  47. }
  48. // List retrieves all clients with optional filtering
  49. func (cs *ClientStore) List(filter map[string]interface{}) ([]*models.Client, error) {
  50. var clients []*models.Client
  51. // Build query from filters
  52. query := cs.db
  53. if filter != nil {
  54. for key, value := range filter {
  55. query = query.Where(key+" = ?", value)
  56. }
  57. }
  58. // Execute query
  59. if err := query.Find(&clients).Error; err != nil {
  60. return nil, fmt.Errorf("failed to list clients: %w", err)
  61. }
  62. return clients, nil
  63. }
  64. // GetClientWithDeployments retrieves a client by ID with associated deployments
  65. func (cs *ClientStore) GetClientWithDeployments(id string) (*models.Client, error) {
  66. var client models.Client
  67. result := cs.db.Preload("Deployments").First(&client, "id = ?", id)
  68. if result.Error != nil {
  69. if result.Error == gorm.ErrRecordNotFound {
  70. return nil, nil // No client found
  71. }
  72. return nil, fmt.Errorf("failed to get client: %w", result.Error)
  73. }
  74. return &client, nil
  75. }