Convert from dao interface to funcs

This was done inorder to support transactions which will be done in
the next PR. This is the first step towards that.
This commit is contained in:
Abin Simon
2022-03-15 17:32:50 +05:30
parent 226b753938
commit df810ab45a
48 changed files with 612 additions and 1255 deletions

View File

@@ -2,7 +2,6 @@ package dao
import (
"context"
"database/sql"
"strings"
"time"
@@ -14,59 +13,7 @@ import (
"github.com/uptrace/bun"
)
// ClusterDao is the interface for cluster operations
type ClusterDao interface {
// create cluster
CreateCluster(ctx context.Context, c *models.Cluster) error
// create or update cluster
UpdateCluster(ctx context.Context, c *models.Cluster) error
//list clusters
ListClusters(ctx context.Context, qo commonv3.QueryOptions) ([]models.Cluster, error)
// delete cluster
DeleteCluster(ctx context.Context, c *models.Cluster) error
// get cluster
GetCluster(ctx context.Context, c *models.Cluster) (*models.Cluster, error)
//get cluster for token
GetClusterForToken(ctx context.Context, token string) (cluster *models.Cluster, err error)
// update relay config information
UpdateClusterAnnotations(ctx context.Context, c *models.Cluster) error
// Notify channel
Notify(chanName, value string) error
}
// clusterDao implements ClusterDao
type clusterDao struct {
cdao pg.EntityDAO
ctdao ClusterTokenDao
pcdao ProjectClusterDao
}
// ClusterDao return new cluster dao
func NewClusterDao(edao pg.EntityDAO) ClusterDao {
return &clusterDao{
cdao: edao,
ctdao: NewClusterTokenDao(edao),
pcdao: NewProjectClusterDao(edao),
}
}
func (s *clusterDao) CreateCluster(ctx context.Context, cluster *models.Cluster) error {
err := s.cdao.GetInstance().RunInTx(ctx, &sql.TxOptions{}, func(ctx context.Context, tx bun.Tx) error {
err := s.createCluster(ctx, cluster, tx)
if err != nil {
return err
}
return nil
})
if err != nil {
return err
}
return nil
}
func (s *clusterDao) createCluster(ctx context.Context, cluster *models.Cluster, tx bun.Tx) error {
func CreateCluster(ctx context.Context, tx bun.Tx, cluster *models.Cluster) error {
clstrToken := &models.ClusterToken{
OrganizationId: cluster.OrganizationId,
@@ -74,7 +21,7 @@ func (s *clusterDao) createCluster(ctx context.Context, cluster *models.Cluster,
ProjectId: cluster.ProjectId,
CreatedAt: time.Now(),
}
err := s.ctdao.CreateToken(ctx, clstrToken)
err := CreateToken(ctx, tx, clstrToken)
if err != nil {
return err
}
@@ -102,9 +49,9 @@ func (s *clusterDao) createCluster(ctx context.Context, cluster *models.Cluster,
return nil
}
func (s *clusterDao) UpdateCluster(ctx context.Context, c *models.Cluster) error {
func UpdateCluster(ctx context.Context, db bun.IDB, c *models.Cluster) error {
_, err := s.cdao.Update(ctx, c.ID, c)
_, err := pg.Update(ctx, db, c.ID, c)
if err != nil {
return err
}
@@ -112,9 +59,9 @@ func (s *clusterDao) UpdateCluster(ctx context.Context, c *models.Cluster) error
return nil
}
func (s *clusterDao) UpdateClusterAnnotations(ctx context.Context, c *models.Cluster) error {
func UpdateClusterAnnotations(ctx context.Context, db bun.IDB, c *models.Cluster) error {
_, err := s.cdao.GetInstance().NewUpdate().Model((*models.Cluster)(nil)).
_, err := db.NewUpdate().Model((*models.Cluster)(nil)).
Set("annotations = ?", c.Annotations).
Where("id = ?", c.ID).Exec(ctx)
if err != nil {
@@ -124,15 +71,15 @@ func (s *clusterDao) UpdateClusterAnnotations(ctx context.Context, c *models.Clu
return nil
}
func (s *clusterDao) GetCluster(ctx context.Context, cluster *models.Cluster) (*models.Cluster, error) {
func GetCluster(ctx context.Context, db bun.IDB, cluster *models.Cluster) (*models.Cluster, error) {
if cluster.ID != uuid.Nil {
_, err := s.cdao.GetByID(ctx, cluster.ID, cluster)
_, err := pg.GetByID(ctx, db, cluster.ID, cluster)
if err != nil {
return nil, err
}
} else {
_, err := s.cdao.GetByName(ctx, cluster.Name, cluster)
_, err := pg.GetByName(ctx, db, cluster.Name, cluster)
if err != nil {
return nil, err
}
@@ -141,8 +88,8 @@ func (s *clusterDao) GetCluster(ctx context.Context, cluster *models.Cluster) (*
return cluster, nil
}
func (s *clusterDao) DeleteCluster(ctx context.Context, c *models.Cluster) error {
_, err := s.cdao.GetInstance().
func DeleteCluster(ctx context.Context, db bun.IDB, c *models.Cluster) error {
_, err := db.
NewUpdate().Model(c).
Set("trash = ?", true).
Set("deleted_at = ?", time.Now()).
@@ -150,28 +97,28 @@ func (s *clusterDao) DeleteCluster(ctx context.Context, c *models.Cluster) error
return err
}
func (s *clusterDao) ListClusters(ctx context.Context, qo commonv3.QueryOptions) (clusters []models.Cluster, err error) {
func ListClusters(ctx context.Context, db bun.IDB, qo commonv3.QueryOptions) (clusters []models.Cluster, err error) {
pid := uuid.NullUUID{UUID: uuid.MustParse(qo.Partner), Valid: true}
oid := uuid.NullUUID{UUID: uuid.MustParse(qo.Organization), Valid: true}
prid := uuid.NullUUID{UUID: uuid.MustParse(qo.Project), Valid: true}
err = s.cdao.ListByProject(ctx, pid, oid, prid, &clusters)
err = pg.ListByProject(ctx, db, pid, oid, prid, &clusters)
if err != nil {
return nil, err
}
return clusters, err
}
func (s *clusterDao) GetClusterForToken(ctx context.Context, token string) (cluster *models.Cluster, err error) {
entity, err := s.cdao.GetX(ctx, "token", token, &models.Cluster{})
func GetClusterForToken(ctx context.Context, db bun.IDB, token string) (cluster *models.Cluster, err error) {
entity, err := pg.GetX(ctx, db, "token", token, &models.Cluster{})
if err != nil {
return nil, err
}
return entity.(*models.Cluster), err
}
func (s *clusterDao) Notify(chanName, value string) error {
_, err := s.cdao.GetInstance().Exec("NOTIFY ?, ?", bun.Ident(chanName), value)
func Notify(db *bun.DB, chanName string, value string) error {
_, err := db.Exec("NOTIFY ?, ?", bun.Ident(chanName), value)
return err
}

View File

@@ -2,7 +2,6 @@ package dao
import (
"context"
"database/sql"
"github.com/RafaySystems/rcloud-base/internal/models"
"github.com/RafaySystems/rcloud-base/internal/persistence/provider/pg"
@@ -12,68 +11,41 @@ import (
var _log = log.GetLogger()
// ClusterOperatorBootstrapDao is the interface for cluster operator bootstrap
type ClusterOperatorBootstrapDao interface {
// create edge operator bootstrap
CreateOperatorBootstrap(ctx context.Context, bootstrap *models.ClusterOperatorBootstrap) error
// GetOperatorBootstrap
GetOperatorBootstrap(ctx context.Context, edgeID string) (*models.ClusterOperatorBootstrap, error)
}
// clusterOperatorBootstrapDao implements ClusterOperatorBootstrapDao
type clusterOperatorBootstrapDao struct {
dao pg.EntityDAO
}
// ClusterOperatorBootstrapDao return new cluster credentials dao
func NewClusterOperatorBootstrapDao(dao pg.EntityDAO) ClusterOperatorBootstrapDao {
return &clusterOperatorBootstrapDao{
dao: dao,
}
}
func (es *clusterOperatorBootstrapDao) CreateOperatorBootstrap(ctx context.Context, bootstrap *models.ClusterOperatorBootstrap) error {
func CreateOperatorBootstrap(ctx context.Context, db bun.Tx, bootstrap *models.ClusterOperatorBootstrap) error {
_log.Infow("CreateOperatorBootstrap: Creating operator bootstrap data", "cluster", bootstrap.ClusterId)
err := es.dao.GetInstance().RunInTx(ctx, &sql.TxOptions{}, func(ctx context.Context, tx bun.Tx) error {
var bstrap *models.ClusterOperatorBootstrap
var bstrap *models.ClusterOperatorBootstrap
entity, err := es.dao.GetX(ctx, "edge_id", bootstrap.ClusterId, &bstrap)
entity, err := pg.GetX(ctx, db, "edge_id", bootstrap.ClusterId, &bstrap)
if err != nil {
_log.Infow("CreateOperatorBootstrap: No existing bootstrap data detected", "edge", bootstrap.ClusterId)
} else {
_log.Infow("CreateOperatorBootstrap: Removing existing bootstrap data", "edge", bootstrap.ClusterId)
bstrap = entity.(*models.ClusterOperatorBootstrap)
err = pg.DeleteX(ctx, db, "edge_id", bstrap.ClusterId, bstrap)
if err != nil {
_log.Infow("CreateOperatorBootstrap: No existing boostrap data detected", "edge", bootstrap.ClusterId)
} else {
_log.Infow("CreateOperatorBootstrap: Removing existing boostrap data", "edge", bootstrap.ClusterId)
bstrap = entity.(*models.ClusterOperatorBootstrap)
err = es.dao.DeleteX(ctx, "edge_id", bstrap.ClusterId, bstrap)
if err != nil {
_log.Errorw("Error while deleting bootstrap data", "Error", err)
return err
}
_log.Infow("CreateOperatorBootstrap: Deleted existing boostrap data", "cluster", bootstrap.ClusterId)
}
_, err = tx.NewInsert().Model(bootstrap).Exec(ctx)
if err != nil {
_log.Errorw("Error inserting bootstrap data", "Error", err)
_log.Errorw("Error while deleting bootstrap data", "Error", err)
return err
}
_log.Infow("Inserted bootstrap data", "cluster", bootstrap.ClusterId)
return nil
})
if err != nil {
_log.Errorw("Exception while adding bootstrap data", "Error:", err)
_log.Infow("CreateOperatorBootstrap: Deleted existing bootstrap data", "cluster", bootstrap.ClusterId)
}
_, err = db.NewInsert().Model(bootstrap).Exec(ctx)
if err != nil {
_log.Errorw("Error inserting bootstrap data", "Error", err)
return err
}
_log.Infow("Inserted bootstrap data", "cluster", bootstrap.ClusterId)
return nil
}
func (es *clusterOperatorBootstrapDao) GetOperatorBootstrap(ctx context.Context, clusterid string) (*models.ClusterOperatorBootstrap, error) {
func GetOperatorBootstrap(ctx context.Context, db bun.IDB, clusterid string) (*models.ClusterOperatorBootstrap, error) {
var bootstrap models.ClusterOperatorBootstrap
entity, err := es.dao.GetX(ctx, "clusterid", clusterid, bootstrap)
entity, err := pg.GetX(ctx, db, "clusterid", clusterid, bootstrap)
if err != nil {
_log.Errorw("Error while fetching bootstrap data using tx ", "Error", err)
return nil, err

View File

@@ -8,6 +8,7 @@ import (
"github.com/RafaySystems/rcloud-base/internal/persistence/provider/pg"
infrav3 "github.com/RafaySystems/rcloud-base/proto/types/infrapb/v3"
"github.com/rs/xid"
"github.com/uptrace/bun"
)
var (
@@ -17,44 +18,24 @@ var (
ErrUsedToken = errors.New("used token")
)
// ClusterTokenDao is the interface for cluster token operations
type ClusterTokenDao interface {
// create cluster token
CreateToken(ctx context.Context, c *models.ClusterToken) error
//register the token
RegisterToken(ctx context.Context, token string) (*models.ClusterToken, error)
}
// clusterTokenDao implements ClusterTokenDao
type clusterTokenDao struct {
dao pg.EntityDAO
}
// ClusterDao return new cluster dao
func NewClusterTokenDao(dao pg.EntityDAO) ClusterTokenDao {
return &clusterTokenDao{
dao: dao,
}
}
// CreateToken creates a token for given cluster name
func (s *clusterTokenDao) CreateToken(ctx context.Context, token *models.ClusterToken) error {
func CreateToken(ctx context.Context, db bun.IDB, token *models.ClusterToken) error {
token.Name = xid.New().String()
_, err := s.dao.Create(ctx, token)
_, err := pg.Create(ctx, db, token)
return err
}
// registerToken registers the cluster token
func (s *clusterTokenDao) RegisterToken(ctx context.Context, token string) (*models.ClusterToken, error) {
func RegisterToken(ctx context.Context, db bun.IDB, token string) (*models.ClusterToken, error) {
entity, err := s.dao.GetX(ctx, "name", token, &models.ClusterToken{})
entity, err := pg.GetX(ctx, db, "name", token, &models.ClusterToken{})
if err != nil {
return nil, ErrInvalidToken
}
ct := entity.(*models.ClusterToken)
ct.State = infrav3.ClusterTokenState_TokenUsed.String()
s.dao.Update(ctx, ct.ID, ct)
pg.Update(ctx, db, ct.ID, ct)
if err != nil {
return nil, ErrInvalidToken
}

View File

@@ -13,37 +13,11 @@ import (
"github.com/uptrace/bun"
)
// ClusterNamespacesDao is the interface for cluster namespaces operations
type ClusterNamespacesDao interface {
// Get Namespace
GetNamespace(ctx context.Context, clusterID uuid.UUID, name string) (models.ClusterNamespace, error)
// GetNamespaces
GetNamespaces(ctx context.Context, clusterID uuid.UUID) ([]models.ClusterNamespace, error)
// GetNamespacesForConditions
GetNamespacesForConditions(ctx context.Context, clusterID uuid.UUID, conditions []scheduler.ClusterNamespaceCondition) ([]models.ClusterNamespace, int, error)
// UpdateNamespaceStatus
UpdateNamespaceStatus(ctx context.Context, updated *models.ClusterNamespace) error
// GetNamespaceHashes
GetNamespaceHashes(ctx context.Context, clusterID uuid.UUID) ([]infrav3.NameHash, error)
}
// clusterNamespacesDao implements ClusterNamespacesDao
type clusterNamespacesDao struct {
dao pg.EntityDAO
}
// ClusterNamespacesDao return new cluster namespaces dao
func NewClusterNamespacesDao(dao pg.EntityDAO) ClusterNamespacesDao {
return &clusterNamespacesDao{
dao: dao,
}
}
func (s clusterNamespacesDao) GetNamespace(ctx context.Context, clusterID uuid.UUID, name string) (models.ClusterNamespace, error) {
func GetNamespace(ctx context.Context, db bun.IDB, clusterID uuid.UUID, name string) (models.ClusterNamespace, error) {
var cn models.ClusterNamespace
err := s.dao.GetInstance().NewSelect().Model(&cn).
err := db.NewSelect().Model(&cn).
Where("cluster_id = ?", clusterID).
Where("name = ?", name).
Scan(ctx)
@@ -55,17 +29,17 @@ func (s clusterNamespacesDao) GetNamespace(ctx context.Context, clusterID uuid.U
return cn, nil
}
func (s clusterNamespacesDao) GetNamespaces(ctx context.Context, clusterID uuid.UUID) ([]models.ClusterNamespace, error) {
func GetNamespaces(ctx context.Context, db bun.IDB, clusterID uuid.UUID) ([]models.ClusterNamespace, error) {
var cns []models.ClusterNamespace
_, err := s.dao.GetX(ctx, "cluster_id", clusterID, &cns)
_, err := pg.GetX(ctx, db, "cluster_id", clusterID, &cns)
return cns, err
}
func (s clusterNamespacesDao) GetNamespacesForConditions(ctx context.Context, clusterID uuid.UUID, conditions []scheduler.ClusterNamespaceCondition) ([]models.ClusterNamespace, int, error) {
func GetNamespacesForConditions(ctx context.Context, db bun.IDB, clusterID uuid.UUID, conditions []scheduler.ClusterNamespaceCondition) ([]models.ClusterNamespace, int, error) {
var cns []models.ClusterNamespace
q := s.dao.GetInstance().NewSelect().Model(&cns).Where("cluster_id = ?", clusterID)
q := db.NewSelect().Model(&cns).Where("cluster_id = ?", clusterID)
for _, condition := range conditions {
q.WhereGroup("", func(sq *bun.SelectQuery) *bun.SelectQuery {
@@ -87,9 +61,9 @@ func (s clusterNamespacesDao) GetNamespacesForConditions(ctx context.Context, cl
return cns, count, err
}
func (s clusterNamespacesDao) UpdateNamespaceStatus(ctx context.Context, updated *models.ClusterNamespace) error {
func UpdateNamespaceStatus(ctx context.Context, db bun.IDB, updated *models.ClusterNamespace) error {
_, err := s.dao.GetInstance().NewUpdate().Model(updated).
_, err := db.NewUpdate().Model(updated).
Set("conditions = ?", updated.Conditions).
Set("status = ?", updated.Status).
Where("cluster_id = ?", updated.ClusterId).
@@ -99,11 +73,11 @@ func (s clusterNamespacesDao) UpdateNamespaceStatus(ctx context.Context, updated
return err
}
func (s clusterNamespacesDao) GetNamespaceHashes(ctx context.Context, clusterID uuid.UUID) ([]infrav3.NameHash, error) {
func GetNamespaceHashes(ctx context.Context, db bun.IDB, clusterID uuid.UUID) ([]infrav3.NameHash, error) {
var nameHashes []infrav3.NameHash
err := s.dao.GetInstance().NewSelect().
err := db.NewSelect().
Model((*models.ClusterNamespace)(nil)).
Column("name", "hash").
//TODO: to be changed to ClusterTaskDeleted later once task is supported

View File

@@ -8,57 +8,34 @@ import (
"github.com/RafaySystems/rcloud-base/pkg/query"
commonv3 "github.com/RafaySystems/rcloud-base/proto/types/commonpb/v3"
"github.com/google/uuid"
"github.com/uptrace/bun"
)
// ProjectClusterDao is the interface for project cluster operations
type ProjectClusterDao interface {
// create project cluster
CreateProjectCluster(ctx context.Context, pc *models.ProjectCluster) error
// get projects for cluster
GetProjectsForCluster(ctx context.Context, clusterID uuid.UUID) ([]models.ProjectCluster, error)
// delete projects for cluster
DeleteProjectsForCluster(ctx context.Context, clusterID uuid.UUID) error
// Validate if the project in scope is owner of the cluster
ValidateClusterAccess(ctx context.Context, opts commonv3.QueryOptions) (bool, error)
}
// projectClusterDao implements ProjectClusterDao
type projectClusterDao struct {
dao pg.EntityDAO
}
// ProjectClusterDao return new project cluster dao
func NewProjectClusterDao(dao pg.EntityDAO) ProjectClusterDao {
return &projectClusterDao{
dao: dao,
}
}
func (s *projectClusterDao) CreateProjectCluster(ctx context.Context, pc *models.ProjectCluster) error {
_, err := s.dao.Create(ctx, pc)
func CreateProjectCluster(ctx context.Context, db bun.IDB, pc *models.ProjectCluster) error {
_, err := pg.Create(ctx, db, pc)
if err != nil {
return err
}
return nil
}
func (s *projectClusterDao) GetProjectsForCluster(ctx context.Context, clusterID uuid.UUID) ([]models.ProjectCluster, error) {
func GetProjectsForCluster(ctx context.Context, db bun.IDB, clusterID uuid.UUID) ([]models.ProjectCluster, error) {
var projectClusters []models.ProjectCluster
err := s.dao.GetInstance().NewSelect().Model(&projectClusters).Where("cluster_id = ?", clusterID).Scan(ctx)
err := db.NewSelect().Model(&projectClusters).Where("cluster_id = ?", clusterID).Scan(ctx)
if err != nil {
return nil, err
}
return projectClusters, nil
}
func (s *projectClusterDao) DeleteProjectsForCluster(ctx context.Context, clusterID uuid.UUID) error {
return s.dao.DeleteX(ctx, "cluster_id", clusterID, &models.ProjectCluster{})
func DeleteProjectsForCluster(ctx context.Context, db bun.IDB, clusterID uuid.UUID) error {
return pg.DeleteX(ctx, db, "cluster_id", clusterID, &models.ProjectCluster{})
}
// Check if the project in scope is owner of the cluster
func (s *projectClusterDao) ValidateClusterAccess(ctx context.Context, opts commonv3.QueryOptions) (bool, error) {
func ValidateClusterAccess(ctx context.Context, db bun.IDB, opts commonv3.QueryOptions) (bool, error) {
var _c models.Cluster
q, err := query.Select(s.dao.GetInstance().NewSelect().Model(&_c), &opts)
q, err := query.Select(db.NewSelect().Model(&_c), &opts)
if err != nil {
return false, err
}

View File

@@ -2,7 +2,6 @@ package dao
import (
"context"
"database/sql"
"errors"
"fmt"
"time"
@@ -17,44 +16,9 @@ import (
"github.com/uptrace/bun"
)
// BootstrapDao is the interface for bootstrap operations
type BootstrapDao interface {
CreateOrUpdateBootstrapInfra(ctx context.Context, infra *models.BootstrapInfra) error
CreateOrUpdateBootstrapAgentTemplate(context.Context, *models.BootstrapAgentTemplate) error
GetBootstrapAgentTemplateForToken(ctx context.Context, token string) (*models.BootstrapAgentTemplate, error)
SelectBootstrapAgentTemplates(ctx context.Context, opts *commonv3.QueryOptions) (ret []models.BootstrapAgentTemplate, count int, err error)
DeleteBootstrapAgentTempate(ctx context.Context, opts *commonv3.QueryOptions, infraRef string) error
GetBootstrapAgents(ctx context.Context, opts *commonv3.QueryOptions, templateRef string) (ret []models.BootstrapAgent, count int, err error)
CreateBootstrapAgent(ctx context.Context, ba *models.BootstrapAgent) error
GetBootstrapAgent(ctx context.Context, templateRef string, opts *commonv3.QueryOptions) (*models.BootstrapAgent, error)
SelectBootstrapAgents(ctx context.Context, templateRef string, opts *commonv3.QueryOptions) (ret []models.BootstrapAgent, count int, err error)
RegisterBootstrapAgent(ctx context.Context, token string) error
DeleteBootstrapAgent(ctx context.Context, templateRef string, opts *commonv3.QueryOptions) error
UpdateBootstrapAgent(ctx context.Context, ba *models.BootstrapAgent, opts *commonv3.QueryOptions) error
GetBootstrapAgentForToken(ctx context.Context, token string) (*models.BootstrapAgent, error)
GetBootstrapAgentTemplateForHost(ctx context.Context, host string) (*models.BootstrapAgentTemplate, error)
GetBootstrapAgentCountForClusterID(ctx context.Context, clusterID string, orgID uuid.UUID) (int, error)
GetBootstrapAgentForClusterID(ctx context.Context, clusterID string, orgID uuid.UUID) (*models.BootstrapAgent, error)
UpdateBootstrapAgentDeleteAt(ctx context.Context, templateRef string) error
UpdateBootstrapAgentTempateDeleteAt(ctx context.Context, opts *commonv3.QueryOptions) error
UpdateBootstrapInfraDeleteAt(ctx context.Context, opts *commonv3.QueryOptions) error
}
func CreateOrUpdateBootstrapInfra(ctx context.Context, db bun.IDB, infra *models.BootstrapInfra) error {
// bootstrapDao implements BootstrapDao
type bootstrapDao struct {
bdao pg.EntityDAO
}
// BootstrapDao return new bootstrap dao
func NewBootstrapDao(edao pg.EntityDAO) BootstrapDao {
return &bootstrapDao{
bdao: edao,
}
}
func (s *bootstrapDao) CreateOrUpdateBootstrapInfra(ctx context.Context, infra *models.BootstrapInfra) error {
_, err := s.bdao.GetInstance().NewInsert().On("CONFLICT (name) DO UPDATE").
_, err := db.NewInsert().On("CONFLICT (name) DO UPDATE").
Set("ca_cert = ?", infra.CaCert).
Set("ca_key = ?", infra.CaKey).
Set("modified_at = ?", time.Now()).
@@ -63,9 +27,9 @@ func (s *bootstrapDao) CreateOrUpdateBootstrapInfra(ctx context.Context, infra *
return err
}
func (s *bootstrapDao) CreateOrUpdateBootstrapAgentTemplate(ctx context.Context, template *models.BootstrapAgentTemplate) error {
func CreateOrUpdateBootstrapAgentTemplate(ctx context.Context, db bun.IDB, template *models.BootstrapAgentTemplate) error {
_, err := s.bdao.GetInstance().NewInsert().On("CONFLICT (name) DO UPDATE").
_, err := db.NewInsert().On("CONFLICT (name) DO UPDATE").
Set("infra_ref = ?", template.InfraRef).
Set("ignore_multiple_register = ?", template.IgnoreMultipleRegister).
Set("auto_register = ?", template.AutoRegister).
@@ -80,14 +44,14 @@ func (s *bootstrapDao) CreateOrUpdateBootstrapAgentTemplate(ctx context.Context,
return err
}
func (s *bootstrapDao) GetBootstrapAgentTemplateForToken(ctx context.Context, token string) (*models.BootstrapAgentTemplate, error) {
func GetBootstrapAgentTemplateForToken(ctx context.Context, db bun.IDB, token string) (*models.BootstrapAgentTemplate, error) {
var template models.BootstrapAgentTemplate
err := s.bdao.GetInstance().NewSelect().Model(&template).Where("token = ?", token).Scan(ctx)
err := db.NewSelect().Model(&template).Where("token = ?", token).Scan(ctx)
return &template, err
}
func (s *bootstrapDao) SelectBootstrapAgentTemplates(ctx context.Context, opts *commonv3.QueryOptions) (ret []models.BootstrapAgentTemplate, count int, err error) {
q, err := query.Select(s.bdao.GetInstance().NewSelect().Model(&ret), opts)
func SelectBootstrapAgentTemplates(ctx context.Context, db bun.IDB, opts *commonv3.QueryOptions) (ret []models.BootstrapAgentTemplate, count int, err error) {
q, err := query.Select(db.NewSelect().Model(&ret), opts)
if err != nil {
return
}
@@ -99,9 +63,9 @@ func (s *bootstrapDao) SelectBootstrapAgentTemplates(ctx context.Context, opts *
return
}
func (s *bootstrapDao) DeleteBootstrapAgentTempate(ctx context.Context, opts *commonv3.QueryOptions, infraRef string) error {
func DeleteBootstrapAgentTempate(ctx context.Context, db bun.IDB, opts *commonv3.QueryOptions, infraRef string) error {
q, err := query.Delete(s.bdao.GetInstance().NewSelect().Model((*models.BootstrapAgentTemplate)(nil)), opts)
q, err := query.Delete(db.NewSelect().Model((*models.BootstrapAgentTemplate)(nil)), opts)
if err != nil {
return err
}
@@ -109,9 +73,9 @@ func (s *bootstrapDao) DeleteBootstrapAgentTempate(ctx context.Context, opts *co
return err
}
func (s *bootstrapDao) GetBootstrapAgent(ctx context.Context, templateRef string, opts *commonv3.QueryOptions) (*models.BootstrapAgent, error) {
func GetBootstrapAgent(ctx context.Context, db bun.IDB, templateRef string, opts *commonv3.QueryOptions) (*models.BootstrapAgent, error) {
var ba models.BootstrapAgent
q, err := query.Get(s.bdao.GetInstance().NewSelect().Model(&ba), opts)
q, err := query.Get(db.NewSelect().Model(&ba), opts)
if err != nil {
return nil, err
}
@@ -127,8 +91,8 @@ func (s *bootstrapDao) GetBootstrapAgent(ctx context.Context, templateRef string
return &ba, err
}
func (s *bootstrapDao) GetBootstrapAgents(ctx context.Context, opts *commonv3.QueryOptions, templateRef string) (ret []models.BootstrapAgent, count int, err error) {
q, err := query.Get(s.bdao.GetInstance().NewSelect().Model(&ret), opts)
func GetBootstrapAgents(ctx context.Context, db bun.IDB, opts *commonv3.QueryOptions, templateRef string) (ret []models.BootstrapAgent, count int, err error) {
q, err := query.Get(db.NewSelect().Model(&ret), opts)
if err != nil {
return nil, 0, err
}
@@ -142,9 +106,9 @@ func (s *bootstrapDao) GetBootstrapAgents(ctx context.Context, opts *commonv3.Qu
return
}
func (s *bootstrapDao) SelectBootstrapAgents(ctx context.Context, templateRef string, opts *commonv3.QueryOptions) (ret []models.BootstrapAgent, count int, err error) {
func SelectBootstrapAgents(ctx context.Context, db bun.IDB, templateRef string, opts *commonv3.QueryOptions) (ret []models.BootstrapAgent, count int, err error) {
q, err := query.Select(s.bdao.GetInstance().NewSelect().Model(&ret), opts)
q, err := query.Select(db.NewSelect().Model(&ret), opts)
if err != nil {
return
}
@@ -158,67 +122,65 @@ func (s *bootstrapDao) SelectBootstrapAgents(ctx context.Context, templateRef st
return
}
func (s *bootstrapDao) CreateBootstrapAgent(ctx context.Context, ba *models.BootstrapAgent) error {
func CreateBootstrapAgent(ctx context.Context, db bun.IDB, ba *models.BootstrapAgent) error {
ba.TokenState = sentry.BootstrapAgentState_NotRegistered.String()
_, err := s.bdao.Create(ctx, ba)
_, err := pg.Create(ctx, db, ba)
return err
}
func (s *bootstrapDao) RegisterBootstrapAgent(ctx context.Context, token string) error {
err := s.bdao.GetInstance().RunInTx(ctx, &sql.TxOptions{}, func(ctx context.Context, tx bun.Tx) error {
ba, err := s.getBootstrapAgentForToken(ctx, token)
if err != nil {
return err
}
bat, err := s.getBootstrapAgentTemplate(ctx, ba.TemplateRef)
if err != nil {
return err
}
state := sentry.BootstrapAgentState_NotApproved
if bat.AutoApprove {
state = sentry.BootstrapAgentState_Approved
}
switch ba.TokenState {
case sentry.BootstrapAgentState_NotRegistered.String():
ba.TokenState = sentry.BootstrapAgentState_Approved.String()
case sentry.BootstrapAgentState_NotApproved.String(), sentry.BootstrapAgentState_Approved.String():
if !bat.IgnoreMultipleRegister {
return fmt.Errorf("cannot register token %s state is %s", token, ba.TokenState)
}
default:
return fmt.Errorf("invalid token state %s", ba.TokenState)
}
_, err = s.bdao.GetInstance().NewUpdate().Model(ba).
Set("token_state = ?", state).
Where("token = ?", token).
Exec(ctx)
// We are explicitly taking in Tx here as it was previously doing RunInTx
// TODO: should we take Tx here or just assume we will be passed in a tx? Or should we create one?
func RegisterBootstrapAgent(ctx context.Context, db bun.Tx, token string) error {
ba, err := getBootstrapAgentForToken(ctx, db, token)
if err != nil {
return err
})
}
bat, err := getBootstrapAgentTemplate(ctx, db, ba.TemplateRef)
if err != nil {
return err
}
state := sentry.BootstrapAgentState_NotApproved
if bat.AutoApprove {
state = sentry.BootstrapAgentState_Approved
}
switch ba.TokenState {
case sentry.BootstrapAgentState_NotRegistered.String():
ba.TokenState = sentry.BootstrapAgentState_Approved.String()
case sentry.BootstrapAgentState_NotApproved.String(), sentry.BootstrapAgentState_Approved.String():
if !bat.IgnoreMultipleRegister {
return fmt.Errorf("cannot register token %s state is %s", token, ba.TokenState)
}
default:
return fmt.Errorf("invalid token state %s", ba.TokenState)
}
_, err = db.NewUpdate().Model(ba).
Set("token_state = ?", state).
Where("token = ?", token).
Exec(ctx)
return err
}
func (s *bootstrapDao) getBootstrapAgentForToken(ctx context.Context, token string) (*models.BootstrapAgent, error) {
func getBootstrapAgentForToken(ctx context.Context, db bun.IDB, token string) (*models.BootstrapAgent, error) {
var ba models.BootstrapAgent
err := s.bdao.GetInstance().NewSelect().Model(&ba).Where("token = ?", token).Scan(ctx)
err := db.NewSelect().Model(&ba).Where("token = ?", token).Scan(ctx)
return &ba, err
}
func (s *bootstrapDao) getBootstrapAgentTemplate(ctx context.Context, name string) (*models.BootstrapAgentTemplate, error) {
func getBootstrapAgentTemplate(ctx context.Context, db bun.IDB, name string) (*models.BootstrapAgentTemplate, error) {
var template models.BootstrapAgentTemplate
err := s.bdao.GetInstance().NewSelect().Model(&template).Where("name = ?", name).Scan(ctx)
err := db.NewSelect().Model(&template).Where("name = ?", name).Scan(ctx)
return &template, err
}
func (s *bootstrapDao) DeleteBootstrapAgent(ctx context.Context, templateRef string, opts *commonv3.QueryOptions) error {
func DeleteBootstrapAgent(ctx context.Context, db bun.IDB, templateRef string, opts *commonv3.QueryOptions) error {
dq := s.bdao.GetInstance().NewDelete().Model((*models.BootstrapAgent)(nil)).Where("name = ?", opts.ID)
dq := db.NewDelete().Model((*models.BootstrapAgent)(nil)).Where("name = ?", opts.ID)
if templateRef != "" {
dq = dq.Where("template_ref = ?", templateRef)
}
@@ -226,22 +188,22 @@ func (s *bootstrapDao) DeleteBootstrapAgent(ctx context.Context, templateRef str
return err
}
func (s *bootstrapDao) UpdateBootstrapAgent(ctx context.Context, ba *models.BootstrapAgent, opts *commonv3.QueryOptions) error {
_, err := s.bdao.GetInstance().NewUpdate().Model(ba).Where("id = ?", ba.ID).Returning("*").Exec(ctx)
func UpdateBootstrapAgent(ctx context.Context, db bun.IDB, ba *models.BootstrapAgent, opts *commonv3.QueryOptions) error {
_, err := db.NewUpdate().Model(ba).Where("id = ?", ba.ID).Returning("*").Exec(ctx)
return err
}
func (s *bootstrapDao) GetBootstrapAgentForToken(ctx context.Context, token string) (*models.BootstrapAgent, error) {
func GetBootstrapAgentForToken(ctx context.Context, db bun.IDB, token string) (*models.BootstrapAgent, error) {
var ba models.BootstrapAgent
err := s.bdao.GetInstance().NewSelect().Model(&ba).Where("token = ?", token).Scan(ctx)
err := db.NewSelect().Model(&ba).Where("token = ?", token).Scan(ctx)
return &ba, err
}
func (s *bootstrapDao) GetBootstrapAgentTemplateForHost(ctx context.Context, host string) (*models.BootstrapAgentTemplate, error) {
func GetBootstrapAgentTemplateForHost(ctx context.Context, db bun.IDB, host string) (*models.BootstrapAgentTemplate, error) {
bat := models.BootstrapAgentTemplate{}
err := s.bdao.GetInstance().NewSelect().Model(&bat).
err := db.NewSelect().Model(&bat).
ColumnExpr("bat.*").
Join("JOIN sentry_bootstrap_template_host as bth").
JoinOn("bat.name = bth.name").
@@ -251,9 +213,9 @@ func (s *bootstrapDao) GetBootstrapAgentTemplateForHost(ctx context.Context, hos
return &bat, err
}
func (s *bootstrapDao) GetBootstrapAgentCountForClusterID(ctx context.Context, clusterID string, orgID uuid.UUID) (int, error) {
func GetBootstrapAgentCountForClusterID(ctx context.Context, db bun.IDB, clusterID string, orgID uuid.UUID) (int, error) {
var ba []models.BootstrapAgent
err := s.bdao.GetInstance().NewSelect().Model(&ba).
err := db.NewSelect().Model(&ba).
Where("name = ?", clusterID).
Where("organization_id = ?", orgID).
Scan(ctx)
@@ -263,9 +225,9 @@ func (s *bootstrapDao) GetBootstrapAgentCountForClusterID(ctx context.Context, c
return len(ba), nil
}
func (s *bootstrapDao) GetBootstrapAgentForClusterID(ctx context.Context, clusterID string, orgID uuid.UUID) (*models.BootstrapAgent, error) {
func GetBootstrapAgentForClusterID(ctx context.Context, db bun.IDB, clusterID string, orgID uuid.UUID) (*models.BootstrapAgent, error) {
var ba models.BootstrapAgent
err := s.bdao.GetInstance().NewSelect().Model(&ba).
err := db.NewSelect().Model(&ba).
Where("name = ?", clusterID).
Where("organization_id = ?", orgID).
Scan(ctx)
@@ -276,9 +238,9 @@ func (s *bootstrapDao) GetBootstrapAgentForClusterID(ctx context.Context, cluste
}
// updateBootstrapAgentDeleteAt builds query for deleting resource
func (s *bootstrapDao) UpdateBootstrapAgentDeleteAt(ctx context.Context, templateRef string) error {
func UpdateBootstrapAgentDeleteAt(ctx context.Context, db bun.IDB, templateRef string) error {
var toBeDeletedAgent *models.BootstrapAgent
_, err := s.bdao.GetX(ctx, "template_ref", templateRef, &toBeDeletedAgent)
_, err := pg.GetX(ctx, db, "template_ref", templateRef, &toBeDeletedAgent)
if err != nil {
return err
}
@@ -289,7 +251,7 @@ func (s *bootstrapDao) UpdateBootstrapAgentDeleteAt(ctx context.Context, templat
opts := &commonv3.QueryOptions{}
query.WithName(toBeDeletedAgent.Name)(opts)
q, err := query.Update(s.bdao.GetInstance().NewUpdate().Model((*models.BootstrapAgent)(nil)), opts)
q, err := query.Update(db.NewUpdate().Model((*models.BootstrapAgent)(nil)), opts)
if err != nil {
return err
}
@@ -300,8 +262,8 @@ func (s *bootstrapDao) UpdateBootstrapAgentDeleteAt(ctx context.Context, templat
return err
}
func (s *bootstrapDao) UpdateBootstrapAgentTempateDeleteAt(ctx context.Context, opts *commonv3.QueryOptions) error {
q, err := query.Update(s.bdao.GetInstance().NewUpdate().Model((*models.BootstrapAgentTemplate)(nil)), opts)
func UpdateBootstrapAgentTempateDeleteAt(ctx context.Context, db bun.IDB, opts *commonv3.QueryOptions) error {
q, err := query.Update(db.NewUpdate().Model((*models.BootstrapAgentTemplate)(nil)), opts)
if err != nil {
return err
}
@@ -313,8 +275,8 @@ func (s *bootstrapDao) UpdateBootstrapAgentTempateDeleteAt(ctx context.Context,
}
// updateBootstrapInfraDeleteAt builds query for deleting resource
func (s *bootstrapDao) UpdateBootstrapInfraDeleteAt(ctx context.Context, opts *commonv3.QueryOptions) error {
q, err := query.Update(s.bdao.GetInstance().NewUpdate().Model((*models.BootstrapInfra)(nil)), opts)
func UpdateBootstrapInfraDeleteAt(ctx context.Context, db bun.IDB, opts *commonv3.QueryOptions) error {
q, err := query.Update(db.NewUpdate().Model((*models.BootstrapInfra)(nil)), opts)
if err != nil {
return err
}

View File

@@ -9,42 +9,20 @@ import (
"github.com/uptrace/bun"
)
type groupDAO struct {
db *bun.DB
}
// Group specific db access
type GroupDAO interface {
Close() error
// get users for group
GetUsers(context.Context, uuid.UUID) ([]models.KratosIdentities, error)
// get roles for group
GetRoles(context.Context, uuid.UUID) ([]*userv3.ProjectNamespaceRole, error)
}
// NewGroupDao return new group dao
func NewGroupDAO(db *bun.DB) *groupDAO {
return &groupDAO{db}
}
func (dao *groupDAO) Close() error {
return dao.db.Close()
}
// GetUsers gets the list of users in a given group
func (dao *groupDAO) GetUsers(ctx context.Context, id uuid.UUID) ([]models.KratosIdentities, error) {
func GetUsers(ctx context.Context, db bun.IDB, id uuid.UUID) ([]models.KratosIdentities, error) {
var entities = []models.KratosIdentities{}
err := dao.db.NewSelect().Model(&entities).
err := db.NewSelect().Model(&entities).
Join(`JOIN authsrv_groupaccount ON identities.id=authsrv_groupaccount.account_id`).
Where(`authsrv_groupaccount.group_id = ?`, id).
Scan(ctx)
return entities, err
}
func (dao *groupDAO) GetRoles(ctx context.Context, id uuid.UUID) ([]*userv3.ProjectNamespaceRole, error) {
func GetGroupRoles(ctx context.Context, db bun.IDB, id uuid.UUID) ([]*userv3.ProjectNamespaceRole, error) {
// Could possibily union them later for some speedup
var r = []*userv3.ProjectNamespaceRole{}
err := dao.db.NewSelect().Table("authsrv_grouprole").
err := db.NewSelect().Table("authsrv_grouprole").
ColumnExpr("authsrv_resourcerole.name as role").
Join(`JOIN authsrv_resourcerole ON authsrv_resourcerole.id=authsrv_grouprole.role_id`).
Where("authsrv_grouprole.group_id = ?", id).
@@ -54,7 +32,7 @@ func (dao *groupDAO) GetRoles(ctx context.Context, id uuid.UUID) ([]*userv3.Proj
}
var pr = []*userv3.ProjectNamespaceRole{}
err = dao.db.NewSelect().Table("authsrv_projectgrouprole").
err = db.NewSelect().Table("authsrv_projectgrouprole").
ColumnExpr("authsrv_resourcerole.name as role, authsrv_project.name as project").
Join(`JOIN authsrv_resourcerole ON authsrv_resourcerole.id=authsrv_projectgrouprole.role_id`).
Join(`JOIN authsrv_project ON authsrv_project.id=authsrv_projectgrouprole.project_id`).
@@ -65,7 +43,7 @@ func (dao *groupDAO) GetRoles(ctx context.Context, id uuid.UUID) ([]*userv3.Proj
}
var pnr = []*userv3.ProjectNamespaceRole{}
err = dao.db.NewSelect().Table("authsrv_projectgroupnamespacerole").
err = db.NewSelect().Table("authsrv_projectgroupnamespacerole").
ColumnExpr("authsrv_resourcerole.name as role, authsrv_project.name as project, namespace_id as namespace").
Join(`JOIN authsrv_resourcerole ON authsrv_resourcerole.id=authsrv_projectgroupnamespacerole.role_id`).
Join(`JOIN authsrv_project ON authsrv_project.id=authsrv_projectgroupnamespacerole.project_id`). // also need a namespace join

View File

@@ -8,36 +8,12 @@ import (
"github.com/RafaySystems/rcloud-base/internal/persistence/provider/pg"
"github.com/RafaySystems/rcloud-base/proto/types/sentry"
"github.com/google/uuid"
"github.com/uptrace/bun"
)
// KubeconfigDao is the interface for kubeconfig operations
type KubeconfigDao interface {
GetKubeconfigRevocation(ctx context.Context, orgID, accountID uuid.UUID, isSSOUser bool) (*models.KubeconfigRevocation, error)
CreateKubeconfigRevocation(ctx context.Context, kr *models.KubeconfigRevocation) error
UpdateKubeconfigRevocation(ctx context.Context, kr *models.KubeconfigRevocation) error
GetKubeconfigSetting(ctx context.Context, orgID, accountID uuid.UUID, issSSO bool) (*models.KubeconfigSetting, error)
CreateKubeconfigSetting(ctx context.Context, ks *models.KubeconfigSetting) error
UpdateKubeconfigSetting(ctx context.Context, ks *models.KubeconfigSetting) error
GetkubectlClusterSettings(ctx context.Context, orgID uuid.UUID, name string) (*models.KubectlClusterSetting, error)
CreatekubectlClusterSettings(ctx context.Context, kc *models.KubectlClusterSetting) error
UpdatekubectlClusterSettings(ctx context.Context, kc *models.KubectlClusterSetting) error
}
// kubeconfigDao implements BootstrapDao
type kubeconfigDao struct {
dao pg.EntityDAO
}
// KubeconfigDao return new kube config dao
func NewKubeconfigDao(edao pg.EntityDAO) KubeconfigDao {
return &kubeconfigDao{
dao: edao,
}
}
func (s *kubeconfigDao) GetKubeconfigRevocation(ctx context.Context, orgID, accountID uuid.UUID, isSSOUser bool) (*models.KubeconfigRevocation, error) {
func GetKubeconfigRevocation(ctx context.Context, db bun.IDB, orgID, accountID uuid.UUID, isSSOUser bool) (*models.KubeconfigRevocation, error) {
var kr models.KubeconfigRevocation
err := s.dao.GetInstance().NewSelect().Model(&kr).
err := db.NewSelect().Model(&kr).
Where("organization_id = ?", orgID).
Where("account_id = ?", accountID).
Where("is_sso_user = ?", isSSOUser).
@@ -45,13 +21,13 @@ func (s *kubeconfigDao) GetKubeconfigRevocation(ctx context.Context, orgID, acco
return &kr, err
}
func (s *kubeconfigDao) CreateKubeconfigRevocation(ctx context.Context, kr *models.KubeconfigRevocation) error {
_, err := s.dao.Create(ctx, kr)
func CreateKubeconfigRevocation(ctx context.Context, db bun.IDB, kr *models.KubeconfigRevocation) error {
_, err := pg.Create(ctx, db, kr)
return err
}
func (s *kubeconfigDao) UpdateKubeconfigRevocation(ctx context.Context, kr *models.KubeconfigRevocation) error {
q := s.dao.GetInstance().NewUpdate().Model(kr)
func UpdateKubeconfigRevocation(ctx context.Context, db bun.IDB, kr *models.KubeconfigRevocation) error {
q := db.NewUpdate().Model(kr)
q = q.Where("organization_id = ?", kr.OrganizationId).
Where("account_id = ?", kr.AccountId).
@@ -63,9 +39,9 @@ func (s *kubeconfigDao) UpdateKubeconfigRevocation(ctx context.Context, kr *mode
return err
}
func (s *kubeconfigDao) GetKubeconfigSetting(ctx context.Context, orgID, accountID uuid.UUID, issSSO bool) (*models.KubeconfigSetting, error) {
func GetKubeconfigSetting(ctx context.Context, db bun.IDB, orgID, accountID uuid.UUID, issSSO bool) (*models.KubeconfigSetting, error) {
var ks models.KubeconfigSetting
err := s.dao.GetInstance().NewSelect().Model(&ks).
err := db.NewSelect().Model(&ks).
Where("organization_id = ?", orgID).
Where("account_id = ?", accountID).
Where("is_sso_user= ?", issSSO).
@@ -73,18 +49,18 @@ func (s *kubeconfigDao) GetKubeconfigSetting(ctx context.Context, orgID, account
return &ks, err
}
func (s *kubeconfigDao) CreateKubeconfigSetting(ctx context.Context, ks *models.KubeconfigSetting) error {
func CreateKubeconfigSetting(ctx context.Context, db bun.IDB, ks *models.KubeconfigSetting) error {
if ks.AccountId == uuid.Nil {
ks.Scope = sentry.KubeconfigSettingOrganizationScope
} else {
ks.Scope = sentry.KubeconfigSettingUserScope
}
_, err := s.dao.Create(ctx, ks)
_, err := pg.Create(ctx, db, ks)
return err
}
func (s *kubeconfigDao) UpdateKubeconfigSetting(ctx context.Context, ks *models.KubeconfigSetting) error {
q := s.dao.GetInstance().NewUpdate().Model(ks)
func UpdateKubeconfigSetting(ctx context.Context, db bun.IDB, ks *models.KubeconfigSetting) error {
q := db.NewUpdate().Model(ks)
q = q.Where("organization_id = ?", ks.OrganizationId).
Where("account_id = ?", ks.AccountId).
@@ -103,21 +79,21 @@ func (s *kubeconfigDao) UpdateKubeconfigSetting(ctx context.Context, ks *models.
return err
}
func (s *kubeconfigDao) GetkubectlClusterSettings(ctx context.Context, orgID uuid.UUID, name string) (*models.KubectlClusterSetting, error) {
func GetkubectlClusterSettings(ctx context.Context, db bun.IDB, orgID uuid.UUID, name string) (*models.KubectlClusterSetting, error) {
var kc models.KubectlClusterSetting
err := s.dao.GetInstance().NewSelect().Model(&kc).
err := db.NewSelect().Model(&kc).
Where("organization_id = ?", orgID).
Where("name = ?", name).Scan(ctx)
return &kc, err
}
func (s *kubeconfigDao) CreatekubectlClusterSettings(ctx context.Context, kc *models.KubectlClusterSetting) error {
_, err := s.dao.Create(ctx, kc)
func CreatekubectlClusterSettings(ctx context.Context, db bun.IDB, kc *models.KubectlClusterSetting) error {
_, err := pg.Create(ctx, db, kc)
return err
}
func (s *kubeconfigDao) UpdatekubectlClusterSettings(ctx context.Context, kc *models.KubectlClusterSetting) error {
q := s.dao.GetInstance().NewUpdate().Model(kc)
func UpdatekubectlClusterSettings(ctx context.Context, db bun.IDB, kc *models.KubectlClusterSetting) error {
q := db.NewUpdate().Model(kc)
q = q.Where("organization_id = ?", kc.OrganizationId).
Where("name = ?", kc.Name)

View File

@@ -4,47 +4,13 @@ import (
"context"
"github.com/RafaySystems/rcloud-base/internal/models"
"github.com/RafaySystems/rcloud-base/internal/persistence/provider/pg"
"github.com/google/uuid"
"github.com/uptrace/bun"
)
// PermissionDao is the interface for permission operations
type PermissionDao interface {
GetGroupPermissions(ctx context.Context, groupNames []string, orgID, partnerID uuid.UUID) ([]models.GroupPermission, error)
GetGroupProjectsByPermission(ctx context.Context, groupNames []string, orgID, partnerID uuid.UUID, permission string) ([]models.GroupPermission, error)
GetGroupPermissionsByProjectIDPermissions(ctx context.Context, groupNames []string, orgID, partnerID uuid.UUID, projects []string, permissions []string) ([]models.GroupPermission, error)
GetProjectByGroup(ctx context.Context, groupNames []string, orgID, partnerID uuid.UUID) ([]models.GroupPermission, error)
GetAccountPermissions(ctx context.Context, accountID, orgID, partnerID uuid.UUID) ([]models.AccountPermission, error)
IsPartnerSuperAdmin(ctx context.Context, accountID, partnerID uuid.UUID) (isPartnerAdmin, isSuperAdmin bool, err error)
GetAccountProjectsByPermission(ctx context.Context, accountID, orgID, partnerID uuid.UUID, permission string) ([]models.AccountPermission, error)
GetAccountPermissionsByProjectIDPermissions(ctx context.Context, accountID, orgID, partnerID uuid.UUID, projects []uuid.UUID, permissions []string) ([]models.AccountPermission, error)
GetSSOUsersGroupProjectRole(ctx context.Context, orgID uuid.UUID) ([]models.SSOAccountGroupProjectRole, error)
GetAcccountsWithApprovalPermission(ctx context.Context, orgID, partnerID uuid.UUID) ([]string, error)
GetSSOAcccountsWithApprovalPermission(ctx context.Context, orgID, partnerID uuid.UUID) ([]string, error)
IsOrgAdmin(ctx context.Context, accountID, partnerID uuid.UUID) (isOrgAdmin bool, err error)
GetAccountBasics(ctx context.Context, accountID uuid.UUID) (*models.Account, error)
GetAccountGroups(ctx context.Context, accountID uuid.UUID) ([]models.GroupAccount, error)
GetDefaultUserGroup(ctx context.Context, orgID uuid.UUID) (*models.Group, error)
GetDefaultUserGroupAccount(ctx context.Context, accountID, groupID uuid.UUID) (*models.GroupAccount, error)
GetDefaultAccountProject(ctx context.Context, accountID uuid.UUID) (models.AccountPermission, error)
}
// permissionDao implements PermissionDao
type permissionDao struct {
dao pg.EntityDAO
}
// PermissionDao return new permission dao
func NewPermissionDao(edao pg.EntityDAO) PermissionDao {
return &permissionDao{
dao: edao,
}
}
func (s *permissionDao) GetGroupPermissions(ctx context.Context, groupNames []string, orgID, partnerID uuid.UUID) ([]models.GroupPermission, error) {
func GetGroupPermissions(ctx context.Context, db bun.IDB, groupNames []string, orgID, partnerID uuid.UUID) ([]models.GroupPermission, error) {
var gps []models.GroupPermission
err := s.dao.GetInstance().NewSelect().Model(&gps).
err := db.NewSelect().Model(&gps).
Where("organization_id = ?", orgID).
Where("partner_id = ?", partnerID).
Where("group_name IN (?)", bun.In(groupNames)).
@@ -52,10 +18,10 @@ func (s *permissionDao) GetGroupPermissions(ctx context.Context, groupNames []st
return gps, err
}
func (s *permissionDao) GetGroupProjectsByPermission(ctx context.Context, groupNames []string, orgID, partnerID uuid.UUID, permission string) ([]models.GroupPermission, error) {
func GetGroupProjectsByPermission(ctx context.Context, db bun.IDB, groupNames []string, orgID, partnerID uuid.UUID, permission string) ([]models.GroupPermission, error) {
var gps []models.GroupPermission
err := s.dao.GetInstance().NewSelect().Model(&gps).
err := db.NewSelect().Model(&gps).
Where("organization_id = ?", orgID).
Where("partner_id = ?", partnerID).
Where("group_name IN (?)", bun.In(groupNames)).
@@ -65,10 +31,10 @@ func (s *permissionDao) GetGroupProjectsByPermission(ctx context.Context, groupN
return gps, err
}
func (s *permissionDao) GetGroupPermissionsByProjectIDPermissions(ctx context.Context, groupNames []string, orgID, partnerID uuid.UUID, projects []string, permissions []string) ([]models.GroupPermission, error) {
func GetGroupPermissionsByProjectIDPermissions(ctx context.Context, db bun.IDB, groupNames []string, orgID, partnerID uuid.UUID, projects []string, permissions []string) ([]models.GroupPermission, error) {
var gps []models.GroupPermission
err := s.dao.GetInstance().NewSelect().Model(&gps).
err := db.NewSelect().Model(&gps).
Where("organization_id = ?", orgID).
Where("partner_id = ?", partnerID).
Where("group_name IN (?)", bun.In(groupNames)).
@@ -79,10 +45,10 @@ func (s *permissionDao) GetGroupPermissionsByProjectIDPermissions(ctx context.Co
return gps, err
}
func (s *permissionDao) GetProjectByGroup(ctx context.Context, groupNames []string, orgID, partnerID uuid.UUID) ([]models.GroupPermission, error) {
func GetProjectByGroup(ctx context.Context, db bun.IDB, groupNames []string, orgID, partnerID uuid.UUID) ([]models.GroupPermission, error) {
var gps []models.GroupPermission
err := s.dao.GetInstance().NewSelect().Model(&gps).
err := db.NewSelect().Model(&gps).
Where("organization_id = ?", orgID).
Where("partner_id = ?", partnerID).
Where("group_name IN (?)", bun.In(groupNames)).
@@ -92,10 +58,10 @@ func (s *permissionDao) GetProjectByGroup(ctx context.Context, groupNames []stri
return gps, err
}
func (a *permissionDao) GetAccountPermissions(ctx context.Context, accountID, orgID, partnerID uuid.UUID) ([]models.AccountPermission, error) {
func GetAccountPermissions(ctx context.Context, db bun.IDB, accountID, orgID, partnerID uuid.UUID) ([]models.AccountPermission, error) {
var aps []models.AccountPermission
err := a.dao.GetInstance().NewSelect().Model(&aps).
err := db.NewSelect().Model(&aps).
Where("account_id = ?", accountID).
Where("organization_id = ?", orgID).
Where("partner_id = ?", partnerID).
@@ -104,13 +70,13 @@ func (a *permissionDao) GetAccountPermissions(ctx context.Context, accountID, or
return aps, err
}
func (a *permissionDao) IsPartnerSuperAdmin(ctx context.Context, accountID, partnerID uuid.UUID) (isPartnerAdmin, isSuperAdmin bool, err error) {
func IsPartnerSuperAdmin(ctx context.Context, db bun.IDB, accountID, partnerID uuid.UUID) (isPartnerAdmin, isSuperAdmin bool, err error) {
var aps []models.AccountPermission
isSuperAdmin = false
isPartnerAdmin = false
err = a.dao.GetInstance().NewSelect().Model(&aps).
err = db.NewSelect().Model(&aps).
Where("account_id = ?", accountID).
Where("partner_id = ?", partnerID).
WhereGroup(" AND ", func(sq *bun.SelectQuery) *bun.SelectQuery {
@@ -133,10 +99,10 @@ func (a *permissionDao) IsPartnerSuperAdmin(ctx context.Context, accountID, part
return isPartnerAdmin, isSuperAdmin, nil
}
func (a *permissionDao) GetAccountProjectsByPermission(ctx context.Context, accountID, orgID, partnerID uuid.UUID, permission string) ([]models.AccountPermission, error) {
func GetAccountProjectsByPermission(ctx context.Context, db bun.IDB, accountID, orgID, partnerID uuid.UUID, permission string) ([]models.AccountPermission, error) {
var aps []models.AccountPermission
err := a.dao.GetInstance().NewSelect().Model(&aps).
err := db.NewSelect().Model(&aps).
Where("account_id = ?", accountID).
Where("organization_id = ?", orgID).
Where("partner_id = ?", partnerID).
@@ -146,10 +112,10 @@ func (a *permissionDao) GetAccountProjectsByPermission(ctx context.Context, acco
return aps, err
}
func (a *permissionDao) GetDefaultAccountProject(ctx context.Context, accountID uuid.UUID) (models.AccountPermission, error) {
func GetDefaultAccountProject(ctx context.Context, db bun.IDB, accountID uuid.UUID) (models.AccountPermission, error) {
var aps models.AccountPermission
err := a.dao.GetInstance().NewSelect().Model(&aps).
err := db.NewSelect().Model(&aps).
ColumnExpr("sap.*").
Join("JOIN authsrv_project as proj").JoinOn("proj.id = sap.project_id").JoinOn("proj.default = ?", true).
Where("account_id = ?", accountID).Limit(1).
@@ -158,10 +124,10 @@ func (a *permissionDao) GetDefaultAccountProject(ctx context.Context, accountID
return aps, err
}
func (a *permissionDao) GetAccountPermissionsByProjectIDPermissions(ctx context.Context, accountID, orgID, partnerID uuid.UUID, projects []uuid.UUID, permissions []string) ([]models.AccountPermission, error) {
func GetAccountPermissionsByProjectIDPermissions(ctx context.Context, db bun.IDB, accountID, orgID, partnerID uuid.UUID, projects []uuid.UUID, permissions []string) ([]models.AccountPermission, error) {
var aps []models.AccountPermission
err := a.dao.GetInstance().NewSelect().Model(&aps).
err := db.NewSelect().Model(&aps).
Where("account_id = ?", accountID).
Where("organization_id = ?", orgID).
Where("partner_id = ?", partnerID).
@@ -172,17 +138,17 @@ func (a *permissionDao) GetAccountPermissionsByProjectIDPermissions(ctx context.
return aps, err
}
func (a *permissionDao) GetSSOUsersGroupProjectRole(ctx context.Context, orgID uuid.UUID) ([]models.SSOAccountGroupProjectRole, error) {
func GetSSOUsersGroupProjectRole(ctx context.Context, db bun.IDB, orgID uuid.UUID) ([]models.SSOAccountGroupProjectRole, error) {
var ssos []models.SSOAccountGroupProjectRole
err := a.dao.GetInstance().NewSelect().Model(&ssos).
err := db.NewSelect().Model(&ssos).
Where("organization_id = ?", orgID).
Scan(ctx)
return ssos, err
}
func (a *permissionDao) GetAcccountsWithApprovalPermission(ctx context.Context, orgID, partnerID uuid.UUID) ([]string, error) {
func GetAcccountsWithApprovalPermission(ctx context.Context, db bun.IDB, orgID, partnerID uuid.UUID) ([]string, error) {
// TODO: remove this from here once Account is structured in types.proto
type accountPermission struct {
bun.BaseModel `bun:"table:sentry_account_permission,alias:sap"`
@@ -190,7 +156,7 @@ func (a *permissionDao) GetAcccountsWithApprovalPermission(ctx context.Context,
*models.AccountPermission
}
var aps []accountPermission
err := a.dao.GetInstance().NewSelect().Model(&aps).
err := db.NewSelect().Model(&aps).
ColumnExpr("ki.traits -> 'email'").
DistinctOn("ki.traits -> 'email'").
Join("INNER JOIN identities as ki ON ?TableAlias.account_id = ki.id").
@@ -213,9 +179,9 @@ func (a *permissionDao) GetAcccountsWithApprovalPermission(ctx context.Context,
return usernames, nil
}
func (a *permissionDao) GetSSOAcccountsWithApprovalPermission(ctx context.Context, orgID, partnerID uuid.UUID) ([]string, error) {
func GetSSOAcccountsWithApprovalPermission(ctx context.Context, db bun.IDB, orgID, partnerID uuid.UUID) ([]string, error) {
var ssoaps []models.SSOAccountGroupProjectRole
err := a.dao.GetInstance().NewSelect().Model(&ssoaps).
err := db.NewSelect().Model(&ssoaps).
Where("?TableAlias.organization_id = ?", orgID).
Where("?TableAlias.partner_id = ?", partnerID).
WhereGroup("grp", func(sq *bun.SelectQuery) *bun.SelectQuery {
@@ -237,12 +203,12 @@ func (a *permissionDao) GetSSOAcccountsWithApprovalPermission(ctx context.Contex
return usernames, nil
}
func (a *permissionDao) IsOrgAdmin(ctx context.Context, accountID, partnerID uuid.UUID) (isOrgAdmin bool, err error) {
func IsOrgAdmin(ctx context.Context, db bun.IDB, accountID, partnerID uuid.UUID) (isOrgAdmin bool, err error) {
var aps []models.AccountPermission
isOrgAdmin = false
err = a.dao.GetInstance().NewSelect().Model(&aps).
err = db.NewSelect().Model(&aps).
Where("account_id = ?", accountID).
Where("partner_id = ?", partnerID).
Where("role_name = ?", "ADMIN").
@@ -262,10 +228,10 @@ func (a *permissionDao) IsOrgAdmin(ctx context.Context, accountID, partnerID uui
return isOrgAdmin, nil
}
func (a *permissionDao) GetAccountBasics(ctx context.Context, accountID uuid.UUID) (*models.Account, error) {
func GetAccountBasics(ctx context.Context, db bun.IDB, accountID uuid.UUID) (*models.Account, error) {
var acc models.Account
err := a.dao.GetInstance().NewSelect().Model(&acc).
err := db.NewSelect().Model(&acc).
Column("identities.id", "traits", "state").
ColumnExpr("max(ks.authenticated_at) as lastlogin").
ColumnExpr("identities.traits -> 'email' as username").
@@ -280,10 +246,10 @@ func (a *permissionDao) GetAccountBasics(ctx context.Context, accountID uuid.UUI
return &acc, nil
}
func (a *permissionDao) GetAccountGroups(ctx context.Context, accountID uuid.UUID) ([]models.GroupAccount, error) {
func GetAccountGroups(ctx context.Context, db bun.IDB, accountID uuid.UUID) ([]models.GroupAccount, error) {
var ga []models.GroupAccount
err := a.dao.GetInstance().NewSelect().Model(&ga).
err := db.NewSelect().Model(&ga).
Where("account_id = ?", accountID).
Where("trash = ?", false).
Where("active = ?", true).
@@ -294,9 +260,9 @@ func (a *permissionDao) GetAccountGroups(ctx context.Context, accountID uuid.UUI
return ga, nil
}
func (a *permissionDao) GetDefaultUserGroup(ctx context.Context, orgID uuid.UUID) (*models.Group, error) {
func GetDefaultUserGroup(ctx context.Context, db bun.IDB, orgID uuid.UUID) (*models.Group, error) {
var g models.Group
err := a.dao.GetInstance().NewSelect().Model(&g).
err := db.NewSelect().Model(&g).
Where("organization_id = ?", orgID).
Where("type = ?", "DEFAULT_USERS").
Where("trash = ?", false).
@@ -304,9 +270,9 @@ func (a *permissionDao) GetDefaultUserGroup(ctx context.Context, orgID uuid.UUID
return &g, err
}
func (a *permissionDao) GetDefaultUserGroupAccount(ctx context.Context, accountID, groupID uuid.UUID) (*models.GroupAccount, error) {
func GetDefaultUserGroupAccount(ctx context.Context, db bun.IDB, accountID, groupID uuid.UUID) (*models.GroupAccount, error) {
var ga models.GroupAccount
err := a.dao.GetInstance().NewSelect().Model(&ga).
err := db.NewSelect().Model(&ga).
Where("account_id = ?", accountID).
Where("group_id = ?", groupID).
Where("trash = ?", false).

View File

@@ -8,30 +8,10 @@ import (
"github.com/uptrace/bun"
)
type roleDAO struct {
db *bun.DB
}
// Role specific db access
type RoleDAO interface {
Close() error
// get permissions for role
GetRolePermissions(context.Context, uuid.UUID) ([]models.ResourcePermission, error)
}
// NewRoleDao return new group dao
func NewRoleDAO(db *bun.DB) *roleDAO {
return &roleDAO{db}
}
func (dao *roleDAO) Close() error {
return dao.db.Close()
}
func (dao *roleDAO) GetRolePermissions(ctx context.Context, id uuid.UUID) ([]models.ResourcePermission, error) {
func GetRolePermissions(ctx context.Context, db bun.IDB, id uuid.UUID) ([]models.ResourcePermission, error) {
// Could possibly union them later for some speedup
var r = []models.ResourcePermission{}
err := dao.db.NewSelect().Table("authsrv_resourcepermission").
err := db.NewSelect().Table("authsrv_resourcepermission").
ColumnExpr("authsrv_resourcepermission.name as name").
Join(`JOIN authsrv_resourcerolepermission ON authsrv_resourcerolepermission.resource_permission_id=authsrv_resourcepermission.id`).
Where("authsrv_resourcerolepermission.resource_role_id = ?", id).

View File

@@ -9,42 +9,19 @@ import (
"github.com/uptrace/bun"
)
type userDAO struct {
db *bun.DB
}
// User specific db access
type UserDAO interface {
Close() error
// get groups for user
GetGroups(context.Context, uuid.UUID) ([]models.Group, error)
// get roles for user
GetRoles(context.Context, uuid.UUID) ([]*userv3.ProjectNamespaceRole, error)
}
// NewUserDao return new user dao
func NewUserDAO(db *bun.DB) *userDAO {
return &userDAO{db}
}
func (dao *userDAO) Close() error {
// XXX: if one dao closes the db connections, won't other have issues?
return dao.db.Close()
}
func (dao *userDAO) GetGroups(ctx context.Context, id uuid.UUID) ([]models.Group, error) {
func GetGroups(ctx context.Context, db bun.IDB, id uuid.UUID) ([]models.Group, error) {
var entities = []models.Group{}
err := dao.db.NewSelect().Model(&entities).
err := db.NewSelect().Model(&entities).
Join(`JOIN authsrv_groupaccount ON authsrv_groupaccount.group_id="group".id`).
Where("authsrv_groupaccount.account_id = ?", id).
Scan(ctx)
return entities, err
}
func (dao *userDAO) GetRoles(ctx context.Context, id uuid.UUID) ([]*userv3.ProjectNamespaceRole, error) {
// Could possibily union them later for some speedup
func GetUserRoles(ctx context.Context, db bun.IDB, id uuid.UUID) ([]*userv3.ProjectNamespaceRole, error) {
// Could possibly union them later for some speedup
var r = []*userv3.ProjectNamespaceRole{}
err := dao.db.NewSelect().Table("authsrv_accountresourcerole").
err := db.NewSelect().Table("authsrv_accountresourcerole").
ColumnExpr("authsrv_resourcerole.name as role").
Join(`JOIN authsrv_resourcerole ON authsrv_resourcerole.id=authsrv_accountresourcerole.role_id`).
Where("authsrv_accountresourcerole.account_id = ?", id).
@@ -54,7 +31,7 @@ func (dao *userDAO) GetRoles(ctx context.Context, id uuid.UUID) ([]*userv3.Proje
}
var pr = []*userv3.ProjectNamespaceRole{}
err = dao.db.NewSelect().Table("authsrv_projectaccountresourcerole").
err = db.NewSelect().Table("authsrv_projectaccountresourcerole").
ColumnExpr("authsrv_resourcerole.name as role, authsrv_project.name as project").
Join(`JOIN authsrv_resourcerole ON authsrv_resourcerole.id=authsrv_projectaccountresourcerole.role_id`).
Join(`JOIN authsrv_project ON authsrv_project.id=authsrv_projectaccountresourcerole.project_id`).
@@ -65,7 +42,7 @@ func (dao *userDAO) GetRoles(ctx context.Context, id uuid.UUID) ([]*userv3.Proje
}
var pnr = []*userv3.ProjectNamespaceRole{}
err = dao.db.NewSelect().Table("authsrv_projectaccountnamespacerole").
err = db.NewSelect().Table("authsrv_projectaccountnamespacerole").
ColumnExpr("authsrv_resourcerole.name as role, authsrv_project.name as project, namespace_id as namespace").
Join(`JOIN authsrv_resourcerole ON authsrv_resourcerole.id=authsrv_projectaccountnamespacerole.role_id`).
Join(`JOIN authsrv_project ON authsrv_project.id=authsrv_projectaccountnamespacerole.project_id`). // also need a namespace join

View File

@@ -8,77 +8,16 @@ import (
bun "github.com/uptrace/bun"
)
// DAO is the interface for database operations
type EntityDAO interface {
Close() error
// create entity
Create(context.Context, interface{}) (interface{}, error)
// get entity by field
GetX(context.Context, string, interface{}, interface{}) (interface{}, error)
// get entity by multiple fields
GetM(context.Context, map[string]interface{}, interface{}) (interface{}, error)
// get entity by id
GetByID(context.Context, uuid.UUID, interface{}) (interface{}, error)
// get entity by name
GetByName(context.Context, string, interface{}) (interface{}, error)
// get entity by name partner and org
GetByNamePartnerOrg(context.Context, string, uuid.NullUUID, uuid.NullUUID, interface{}) (interface{}, error)
// get entity id by name
GetIdByName(context.Context, string, interface{}) (interface{}, error)
// get entity id by name partner and org
GetIdByNamePartnerOrg(context.Context, string, uuid.NullUUID, uuid.NullUUID, interface{}) (interface{}, error)
// get entity name by id
GetNameById(context.Context, uuid.UUID, interface{}) (interface{}, error)
//Update entity
Update(context.Context, uuid.UUID, interface{}) (interface{}, error)
// get entity by field
UpdateX(context.Context, string, interface{}, interface{}) (interface{}, error)
// delete entity by field
DeleteX(context.Context, string, interface{}, interface{}) error
// delete entity
Delete(context.Context, uuid.UUID, interface{}) error
// delete all items in table (for script)
HardDeleteAll(context.Context, interface{}) error
// get list of entities
List(context.Context, uuid.NullUUID, uuid.NullUUID, interface{}) (interface{}, error)
// get list of entities
ListByProject(context.Context, uuid.NullUUID, uuid.NullUUID, uuid.NullUUID, interface{}) error
// get list of entities without filtering
ListAll(context.Context, interface{}) (interface{}, error)
// lookup user by traits
GetByTraits(ctx context.Context, name string, entity interface{}) (interface{}, error)
// lookup user id by traits
GetIdByTraits(ctx context.Context, name string, entity interface{}) (interface{}, error)
//returns db object
GetInstance() *bun.DB
}
type entityDAO struct {
db *bun.DB
}
func (dao *entityDAO) Close() error {
return dao.db.Close()
}
// NewEntityDao return new entity dao
func NewEntityDAO(db *bun.DB) EntityDAO {
return &entityDAO{db}
}
func (dao *entityDAO) Create(ctx context.Context, entity interface{}) (interface{}, error) {
if _, err := dao.db.NewInsert().Model(entity).Exec(ctx); err != nil {
func Create(ctx context.Context, db bun.IDB, entity interface{}) (interface{}, error) {
if _, err := db.NewInsert().Model(entity).Exec(ctx); err != nil {
return nil, err
}
return entity, nil
}
func (dao *entityDAO) GetX(ctx context.Context, field string, value interface{}, entity interface{}) (interface{}, error) {
err := dao.db.NewSelect().Model(entity).
func GetX(ctx context.Context, db bun.IDB, field string, value interface{}, entity interface{}) (interface{}, error) {
err := db.NewSelect().Model(entity).
Where(fmt.Sprintf("%s = ?", field), value).
Where("trash = ?", false).
Scan(ctx)
@@ -90,9 +29,9 @@ func (dao *entityDAO) GetX(ctx context.Context, field string, value interface{},
}
// M for multi ;)
func (dao *entityDAO) GetM(ctx context.Context, checks map[string]interface{}, entity interface{}) (interface{}, error) {
func GetM(ctx context.Context, db bun.IDB, checks map[string]interface{}, entity interface{}) (interface{}, error) {
// Can we get the checks directly from entity and create an upsert sort of func?
q := dao.db.NewSelect().Model(entity)
q := db.NewSelect().Model(entity)
for field := range checks {
q.Where(fmt.Sprintf("%s = ?", field), checks[field])
}
@@ -104,8 +43,8 @@ func (dao *entityDAO) GetM(ctx context.Context, checks map[string]interface{}, e
return entity, nil
}
func (dao *entityDAO) GetByID(ctx context.Context, id uuid.UUID, entity interface{}) (interface{}, error) {
err := dao.db.NewSelect().Model(entity).
func GetByID(ctx context.Context, db bun.IDB, id uuid.UUID, entity interface{}) (interface{}, error) {
err := db.NewSelect().Model(entity).
Where("id = ?", id).
Where("trash = ?", false).
Scan(ctx)
@@ -116,8 +55,8 @@ func (dao *entityDAO) GetByID(ctx context.Context, id uuid.UUID, entity interfac
return entity, nil
}
func (dao *entityDAO) GetByName(ctx context.Context, name string, entity interface{}) (interface{}, error) {
err := dao.db.NewSelect().Model(entity).
func GetByName(ctx context.Context, db bun.IDB, name string, entity interface{}) (interface{}, error) {
err := db.NewSelect().Model(entity).
Where("name = ?", name).
Where("trash = ?", false).
Scan(ctx)
@@ -127,8 +66,8 @@ func (dao *entityDAO) GetByName(ctx context.Context, name string, entity interfa
return entity, nil
}
func (dao *entityDAO) GetByNamePartnerOrg(ctx context.Context, name string, pid uuid.NullUUID, oid uuid.NullUUID, entity interface{}) (interface{}, error) {
sq := dao.db.NewSelect().Model(entity)
func GetByNamePartnerOrg(ctx context.Context, db bun.IDB, name string, pid uuid.NullUUID, oid uuid.NullUUID, entity interface{}) (interface{}, error) {
sq := db.NewSelect().Model(entity)
if oid.Valid {
sq = sq.Where("organization_id = ?", oid)
}
@@ -146,8 +85,8 @@ func (dao *entityDAO) GetByNamePartnerOrg(ctx context.Context, name string, pid
return entity, nil
}
func (dao *entityDAO) GetIdByName(ctx context.Context, name string, entity interface{}) (interface{}, error) {
err := dao.db.NewSelect().Column("id").Model(entity).
func GetIdByName(ctx context.Context, db bun.IDB, name string, entity interface{}) (interface{}, error) {
err := db.NewSelect().Column("id").Model(entity).
Where("name = ?", name).
Where("trash = ?", false).
Scan(ctx)
@@ -158,8 +97,8 @@ func (dao *entityDAO) GetIdByName(ctx context.Context, name string, entity inter
return entity, nil
}
func (dao *entityDAO) GetIdByNamePartnerOrg(ctx context.Context, name string, pid uuid.NullUUID, oid uuid.NullUUID, entity interface{}) (interface{}, error) {
sq := dao.db.NewSelect().Column("id").Model(entity)
func GetIdByNamePartnerOrg(ctx context.Context, db bun.IDB, name string, pid uuid.NullUUID, oid uuid.NullUUID, entity interface{}) (interface{}, error) {
sq := db.NewSelect().Column("id").Model(entity)
if oid.Valid {
sq = sq.Where("organization_id = ?", oid)
}
@@ -177,8 +116,8 @@ func (dao *entityDAO) GetIdByNamePartnerOrg(ctx context.Context, name string, pi
return entity, nil
}
func (dao *entityDAO) GetNameById(ctx context.Context, id uuid.UUID, entity interface{}) (interface{}, error) {
err := dao.db.NewSelect().Column("name").Model(entity).
func GetNameById(ctx context.Context, db bun.IDB, id uuid.UUID, entity interface{}) (interface{}, error) {
err := db.NewSelect().Column("name").Model(entity).
Where("id = ?", id).
Where("trash = ?", false).
Scan(ctx)
@@ -189,22 +128,22 @@ func (dao *entityDAO) GetNameById(ctx context.Context, id uuid.UUID, entity inte
return entity, nil
}
func (dao *entityDAO) Update(ctx context.Context, id uuid.UUID, entity interface{}) (interface{}, error) {
if _, err := dao.db.NewUpdate().Model(entity).Where("id = ?", id).Exec(ctx); err != nil {
func Update(ctx context.Context, db bun.IDB, id uuid.UUID, entity interface{}) (interface{}, error) {
if _, err := db.NewUpdate().Model(entity).Where("id = ?", id).Exec(ctx); err != nil {
return nil, err
}
return entity, nil
}
func (dao *entityDAO) UpdateX(ctx context.Context, field string, value interface{}, entity interface{}) (interface{}, error) {
if _, err := dao.db.NewUpdate().Model(entity).Where("? = ?", bun.Ident(field), value).Exec(ctx); err != nil {
func UpdateX(ctx context.Context, db bun.IDB, field string, value interface{}, entity interface{}) (interface{}, error) {
if _, err := db.NewUpdate().Model(entity).Where("? = ?", bun.Ident(field), value).Exec(ctx); err != nil {
return nil, err
}
return entity, nil
}
func (dao *entityDAO) Delete(ctx context.Context, id uuid.UUID, entity interface{}) error {
_, err := dao.db.NewUpdate().
func Delete(ctx context.Context, db bun.IDB, id uuid.UUID, entity interface{}) error {
_, err := db.NewUpdate().
Model(entity).
Column("trash").
Where("id = ?", id).
@@ -213,8 +152,8 @@ func (dao *entityDAO) Delete(ctx context.Context, id uuid.UUID, entity interface
return err
}
func (dao *entityDAO) DeleteX(ctx context.Context, field string, value interface{}, entity interface{}) error {
_, err := dao.db.NewUpdate().
func DeleteX(ctx context.Context, db bun.IDB, field string, value interface{}, entity interface{}) error {
_, err := db.NewUpdate().
Model(entity).
Column("trash").
Where("? = ?", bun.Ident(field), value).
@@ -224,16 +163,16 @@ func (dao *entityDAO) DeleteX(ctx context.Context, field string, value interface
}
// HardDeleteAll deletes all records in a table (primarily for use in scripts)
func (dao *entityDAO) HardDeleteAll(ctx context.Context, entity interface{}) error {
_, err := dao.db.NewDelete().
func HardDeleteAll(ctx context.Context, db bun.IDB, entity interface{}) error {
_, err := db.NewDelete().
Model(entity).
Where("1 = 1"). // TODO: see how to remove this
Exec(ctx)
return err
}
func (dao *entityDAO) List(ctx context.Context, partnerId uuid.NullUUID, organizationId uuid.NullUUID, entities interface{}) (interface{}, error) {
sq := dao.db.NewSelect().Model(entities)
func List(ctx context.Context, db bun.IDB, partnerId uuid.NullUUID, organizationId uuid.NullUUID, entities interface{}) (interface{}, error) {
sq := db.NewSelect().Model(entities)
if partnerId.Valid {
sq = sq.Where("partner_id = ?", partnerId)
}
@@ -245,8 +184,8 @@ func (dao *entityDAO) List(ctx context.Context, partnerId uuid.NullUUID, organiz
return entities, err
}
func (dao *entityDAO) ListByProject(ctx context.Context, partnerId uuid.NullUUID, organizationId uuid.NullUUID, projectId uuid.NullUUID, entities interface{}) error {
sq := dao.db.NewSelect().Model(entities)
func ListByProject(ctx context.Context, db bun.IDB, partnerId uuid.NullUUID, organizationId uuid.NullUUID, projectId uuid.NullUUID, entities interface{}) error {
sq := db.NewSelect().Model(entities)
if partnerId.Valid {
sq = sq.Where("partner_id = ?", partnerId)
}
@@ -261,16 +200,15 @@ func (dao *entityDAO) ListByProject(ctx context.Context, partnerId uuid.NullUUID
return err
}
func (dao *entityDAO) ListAll(ctx context.Context, entities interface{}) (interface{}, error) {
err := dao.db.NewSelect().Model(entities).Scan(ctx)
func ListAll(ctx context.Context, db bun.IDB, entities interface{}) (interface{}, error) {
err := db.NewSelect().Model(entities).Scan(ctx)
return entities, err
}
func (dao *entityDAO) GetByTraits(ctx context.Context, name string, entity interface{}) (interface{}, error) {
func GetByTraits(ctx context.Context, db bun.IDB, name string, entity interface{}) (interface{}, error) {
// TODO: better name and possibly pass in trait name
err := dao.db.NewSelect().Model(entity).
err := db.NewSelect().Model(entity).
Where("traits ->> 'email' = ?", name).
Where("trash = ?", false).
Scan(ctx)
if err != nil {
return nil, err
@@ -279,11 +217,10 @@ func (dao *entityDAO) GetByTraits(ctx context.Context, name string, entity inter
return entity, nil
}
func (dao *entityDAO) GetIdByTraits(ctx context.Context, name string, entity interface{}) (interface{}, error) {
func GetIdByTraits(ctx context.Context, db bun.IDB, name string, entity interface{}) (interface{}, error) {
// TODO: better name and possibly pass in trait name
err := dao.db.NewSelect().Column("id").Model(entity).
err := db.NewSelect().Column("id").Model(entity).
Where("traits ->> 'email' = ?", name).
Where("trash = ?", false).
Scan(ctx)
if err != nil {
return nil, err
@@ -291,7 +228,3 @@ func (dao *entityDAO) GetIdByTraits(ctx context.Context, name string, entity int
return entity, nil
}
func (dao *entityDAO) GetInstance() *bun.DB {
return dao.db
}

View File

@@ -0,0 +1,76 @@
package pg
import (
"context"
"fmt"
"github.com/RafaySystems/rcloud-base/internal/models"
"github.com/google/uuid"
"github.com/uptrace/bun"
)
func GetPartnerId(ctx context.Context, db bun.IDB, name string) (uuid.UUID, error) {
entity, err := GetIdByName(ctx, db, name, &models.Partner{})
if err != nil {
return uuid.Nil, err
}
if prt, ok := entity.(*models.Partner); ok {
return prt.ID, nil
}
return uuid.Nil, fmt.Errorf("no partner found with name %v", name)
}
func GetOrganizationId(ctx context.Context, db bun.IDB, name string) (uuid.UUID, error) {
entity, err := GetIdByName(ctx, db, name, &models.Organization{})
if err != nil {
return uuid.Nil, err
}
if org, ok := entity.(*models.Organization); ok {
return org.ID, nil
}
return uuid.Nil, fmt.Errorf("no organization found with name %v", name)
}
func GetProjectId(ctx context.Context, db bun.IDB, name string) (uuid.UUID, error) {
entity, err := GetIdByName(ctx, db, name, &models.Project{})
if err != nil {
return uuid.Nil, err
}
if proj, ok := entity.(*models.Project); ok {
return proj.ID, nil
}
return uuid.Nil, fmt.Errorf("no project found with name %v", name)
}
func GetPartnerName(ctx context.Context, db bun.IDB, id uuid.UUID) (string, error) {
entity, err := GetNameById(ctx, db, id, &models.Partner{})
if err != nil {
return "", err
}
if prt, ok := entity.(*models.Partner); ok {
return prt.Name, nil
}
return "", fmt.Errorf("no partner found with id %v", id)
}
func GetOrganizationName(ctx context.Context, db bun.IDB, id uuid.UUID) (string, error) {
entity, err := GetNameById(ctx, db, id, &models.Organization{})
if err != nil {
return "", err
}
if org, ok := entity.(*models.Organization); ok {
return org.Name, nil
}
return "", fmt.Errorf("no organization found with id %v", id)
}
func GetProjectName(ctx context.Context, db bun.IDB, id uuid.UUID) (string, error) {
entity, err := GetNameById(ctx, db, id, &models.Project{})
if err != nil {
return "", err
}
if proj, ok := entity.(*models.Project); ok {
return proj.Name, nil
}
return "", fmt.Errorf("no project found with id %v", id)
}

View File

@@ -1,98 +0,0 @@
package utils
import (
"context"
"fmt"
"github.com/RafaySystems/rcloud-base/internal/models"
"github.com/RafaySystems/rcloud-base/internal/persistence/provider/pg"
"github.com/google/uuid"
"github.com/uptrace/bun"
)
// TODO: could use a better name
type lookup struct {
dao pg.EntityDAO
}
type Lookup interface {
GetPartnerId(context.Context, string) (uuid.UUID, error)
GetOrganizationId(context.Context, string) (uuid.UUID, error)
GetProjectId(context.Context, string) (uuid.UUID, error)
GetPartnerName(context.Context, uuid.UUID) (string, error)
GetOrganizationName(context.Context, uuid.UUID) (string, error)
GetProjectName(context.Context, uuid.UUID) (string, error)
}
func NewLookup(db *bun.DB) Lookup {
return &lookup{
dao: pg.NewEntityDAO(db),
}
}
func (l *lookup) GetPartnerId(ctx context.Context, name string) (uuid.UUID, error) {
entity, err := l.dao.GetIdByName(ctx, name, &models.Partner{})
if err != nil {
return uuid.Nil, err
}
if prt, ok := entity.(*models.Partner); ok {
return prt.ID, nil
}
return uuid.Nil, fmt.Errorf("no partner found with name %v", name)
}
func (l *lookup) GetOrganizationId(ctx context.Context, name string) (uuid.UUID, error) {
entity, err := l.dao.GetIdByName(ctx, name, &models.Organization{})
if err != nil {
return uuid.Nil, err
}
if org, ok := entity.(*models.Organization); ok {
return org.ID, nil
}
return uuid.Nil, fmt.Errorf("no organization found with name %v", name)
}
func (l *lookup) GetProjectId(ctx context.Context, name string) (uuid.UUID, error) {
entity, err := l.dao.GetIdByName(ctx, name, &models.Project{})
if err != nil {
return uuid.Nil, err
}
if proj, ok := entity.(*models.Project); ok {
return proj.ID, nil
}
return uuid.Nil, fmt.Errorf("no project found with name %v", name)
}
func (l *lookup) GetPartnerName(ctx context.Context, id uuid.UUID) (string, error) {
entity, err := l.dao.GetNameById(ctx, id, &models.Partner{})
if err != nil {
return "", err
}
if prt, ok := entity.(*models.Partner); ok {
return prt.Name, nil
}
return "", fmt.Errorf("no partner found with id %v", id)
}
func (l *lookup) GetOrganizationName(ctx context.Context, id uuid.UUID) (string, error) {
entity, err := l.dao.GetNameById(ctx, id, &models.Organization{})
if err != nil {
return "", err
}
if org, ok := entity.(*models.Organization); ok {
return org.Name, nil
}
return "", fmt.Errorf("no organization found with id %v", id)
}
func (l *lookup) GetProjectName(ctx context.Context, id uuid.UUID) (string, error) {
entity, err := l.dao.GetNameById(ctx, id, &models.Project{})
if err != nil {
return "", err
}
if proj, ok := entity.(*models.Project); ok {
return proj.Name, nil
}
return "", fmt.Errorf("no project found with id %v", id)
}