component.go 2.4 KB

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