12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788 |
- package dbstore
- import (
- "fmt"
- "git.linuxforward.com/byop/byop-engine/dbmanager"
- "git.linuxforward.com/byop/byop-engine/models"
- "gorm.io/gorm"
- )
- // ClientStore handles database operations for clients
- type ClientStore struct {
- db *gorm.DB
- }
- // NewClientStore creates a new ClientStore
- func NewClientStore(dbManager dbmanager.DbManager) *ClientStore {
- return &ClientStore{
- db: dbManager.GetDB(),
- }
- }
- // Create creates a new client
- func (cs *ClientStore) Create(client *models.Client) error {
- // GORM will handle ID auto-increment, created_at and updated_at automatically
- return cs.db.Create(client).Error
- }
- // GetByID retrieves a client by ID
- func (cs *ClientStore) GetByID(id int64) (*models.Client, error) {
- var client models.Client
- result := cs.db.
- Where("rowid = ?", id). // Use SQLite's rowid explicitly
- First(&client)
- if result.Error != nil {
- if result.Error == gorm.ErrRecordNotFound {
- return nil, nil // No client found
- }
- return nil, fmt.Errorf("failed to get client: %w", result.Error)
- }
- return &client, nil
- }
- // Update updates an existing client
- func (cs *ClientStore) Update(client *models.Client) error {
- return cs.db.Save(client).Error
- }
- // Delete deletes a client by ID
- func (cs *ClientStore) Delete(id int64) error {
- return cs.db.Delete(&models.Client{}, "id = ?", id).Error
- }
- // List retrieves all clients with optional filtering
- func (cs *ClientStore) List(filter map[string]interface{}) ([]*models.Client, error) {
- var clients []*models.Client
- // Build query from filters
- query := cs.db
- if filter != nil {
- for key, value := range filter {
- query = query.Where(key+" = ?", value)
- }
- }
- // Execute query
- if err := query.Find(&clients).Error; err != nil {
- return nil, fmt.Errorf("failed to list clients: %w", err)
- }
- return clients, nil
- }
- // GetClientWithDeployments retrieves a client by ID with associated deployments
- func (cs *ClientStore) GetClientWithDeployments(id int64) (*models.Client, error) {
- var client models.Client
- result := cs.db.Preload("Deployments").
- Where("rowid = ?", id). // Use SQLite's rowid explicitly
- First(&client)
- if result.Error != nil {
- if result.Error == gorm.ErrRecordNotFound {
- return nil, nil // No client found
- }
- return nil, fmt.Errorf("failed to get client: %w", result.Error)
- }
- return &client, nil
- }
|