apollo-backend/internal/data/device_accounts.go

46 lines
926 B
Go
Raw Normal View History

2021-05-10 00:51:15 +00:00
package data
2021-07-13 14:17:20 +00:00
import (
"context"
"github.com/jackc/pgx/v4/pgxpool"
)
2021-05-10 00:51:15 +00:00
type DeviceAccount struct {
ID int64
AccountID int64
DeviceID int64
}
type DeviceAccountModel struct {
2021-07-13 14:17:20 +00:00
ctx context.Context
pool *pgxpool.Pool
2021-05-10 00:51:15 +00:00
}
func (dam *DeviceAccountModel) Associate(accountID int64, deviceID int64) error {
2021-07-13 14:17:20 +00:00
stmt := `
2021-05-10 00:51:15 +00:00
INSERT INTO devices_accounts (account_id, device_id)
VALUES ($1, $2)
ON CONFLICT (account_id, device_id) DO NOTHING
RETURNING id`
2021-07-13 14:17:20 +00:00
if _, err := dam.pool.Exec(dam.ctx, stmt, accountID, deviceID); err != nil {
2021-05-10 00:51:15 +00:00
return err
}
// Update account counter
2021-07-13 14:17:20 +00:00
stmt = `
2021-05-10 00:51:15 +00:00
UPDATE accounts
SET device_count = (
SELECT COUNT(*) FROM devices_accounts WHERE account_id = $1
)
WHERE id = $1`
2021-07-13 14:17:20 +00:00
_, err := dam.pool.Exec(dam.ctx, stmt, accountID)
return err
2021-05-10 00:51:15 +00:00
}
type MockDeviceAccountModel struct{}
func (mdam *MockDeviceAccountModel) Associate(accountID int64, deviceID int64) error {
return nil
}