client.go 2.3 KB

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