db

package
v0.0.0-...-26e1ad0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: May 28, 2024 License: Apache-2.0 Imports: 16 Imported by: 0

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func BuildSimpleWhereClause

func BuildSimpleWhereClause(fields map[string]any, parameterOffset int) (queryFragment string, queryArgs []any)

BuildSimpleWhereClause constructs a WHERE clause of the form "field1 = val1 AND field2 = val2 AND field3 IN (val3, val4)".

If parameterOffset is not 0, start counting placeholders ("$1", "$2", etc.) after that offset.

func CompareResourceRefs

func CompareResourceRefs[I ~int64](lhs, rhs ResourceRef[I]) int

CompareResourceRefs is a compare function for ResourceRef (for use with slices.SortFunc etc.)

func Init

func Init() (*gorp.DbMap, error)

Init initializes the connection to the database.

func InitFromURL

func InitFromURL(dbURL *url.URL) (*gorp.DbMap, error)

InitFromURL is like Init, but takes an explicit URL. This is used to override the default database URL configuration in tests.

Types

type ClusterAZResource

type ClusterAZResource struct {
	ID                ClusterAZResourceID    `db:"id"`
	ResourceID        ClusterResourceID      `db:"resource_id"`
	AvailabilityZone  limes.AvailabilityZone `db:"az"`
	RawCapacity       uint64                 `db:"raw_capacity"`
	Usage             *uint64                `db:"usage"`
	SubcapacitiesJSON string                 `db:"subcapacities"`
}

ClusterAZResource contains a record from the `cluster_az_resources` table.

type ClusterAZResourceID

type ClusterAZResourceID int64

ClusterAZResourceID is an ID into the cluster_az_resources table. This typedef is used to distinguish these IDs from IDs of other tables or raw int64 values.

type ClusterCapacitor

type ClusterCapacitor struct {
	CapacitorID        string     `db:"capacitor_id"`
	ScrapedAt          *time.Time `db:"scraped_at"` // pointer type to allow for NULL value
	ScrapeDurationSecs float64    `db:"scrape_duration_secs"`
	SerializedMetrics  string     `db:"serialized_metrics"`
	NextScrapeAt       time.Time  `db:"next_scrape_at"`
	ScrapeErrorMessage string     `db:"scrape_error_message"`
}

ClusterCapacitor contains a record from the `cluster_capacitors` table.

type ClusterResource

type ClusterResource struct {
	ID          ClusterResourceID           `db:"id"`
	CapacitorID string                      `db:"capacitor_id"`
	ServiceID   ClusterServiceID            `db:"service_id"`
	Name        limesresources.ResourceName `db:"name"`
}

ClusterResource contains a record from the `cluster_resources` table.

func (ClusterResource) Ref

Ref returns the ResourceRef for this resource.

type ClusterResourceID

type ClusterResourceID int64

ClusterResourceID is an ID into the cluster_resources table. This typedef is used to distinguish these IDs from IDs of other tables or raw int64 values.

type ClusterService

type ClusterService struct {
	ID   ClusterServiceID  `db:"id"`
	Type limes.ServiceType `db:"type"`
}

ClusterService contains a record from the `cluster_services` table.

type ClusterServiceID

type ClusterServiceID int64

ClusterServiceID is an ID into the cluster_services table. This typedef is used to distinguish these IDs from IDs of other tables or raw int64 values.

type CommitmentState

type CommitmentState string

CommitmentState is an enum. The possible values below are sorted in roughly chronological order.

const (
	CommitmentStatePlanned    CommitmentState = "planned"
	CommitmentStatePending    CommitmentState = "pending"
	CommitmentStateActive     CommitmentState = "active"
	CommitmentStateSuperseded CommitmentState = "superseded"
	CommitmentStateExpired    CommitmentState = "expired"
)

type Domain

type Domain struct {
	ID   DomainID `db:"id"`
	Name string   `db:"name"`
	UUID string   `db:"uuid"`
}

Domain contains a record from the `domains` table.

type DomainID

type DomainID int64

DomainID is an ID into the domains table. This typedef is used to distinguish these IDs from IDs of other tables or raw int64 values.

type Interface

type Interface interface {
	// from database/sql
	sqlext.Executor

	// from github.com/go-gorp/gorp
	Insert(args ...any) error
	Update(args ...any) (int64, error)
	Delete(args ...any) (int64, error)
	Select(i any, query string, args ...any) ([]any, error)
}

Interface provides the common methods that both SQL connections and transactions implement.

type Project

type Project struct {
	ID         ProjectID `db:"id"`
	DomainID   DomainID  `db:"domain_id"`
	Name       string    `db:"name"`
	UUID       string    `db:"uuid"`
	ParentUUID string    `db:"parent_uuid"`
}

Project contains a record from the `projects` table.

type ProjectAZResource

type ProjectAZResource struct {
	ID                  ProjectAZResourceID    `db:"id"`
	ResourceID          ProjectResourceID      `db:"resource_id"`
	AvailabilityZone    limes.AvailabilityZone `db:"az"`
	Quota               *uint64                `db:"quota"`
	Usage               uint64                 `db:"usage"`
	PhysicalUsage       *uint64                `db:"physical_usage"`
	SubresourcesJSON    string                 `db:"subresources"`
	HistoricalUsageJSON string                 `db:"historical_usage"`
}

ProjectAZResource contains a record from the `project_az_resources` table.

type ProjectAZResourceID

type ProjectAZResourceID int64

ProjectAZResourceID is an ID into the project_az_resources table. This typedef is used to distinguish these IDs from IDs of other tables or raw int64 values.

type ProjectCommitment

type ProjectCommitment struct {
	ID           ProjectCommitmentID               `db:"id"`
	AZResourceID ProjectAZResourceID               `db:"az_resource_id"`
	Amount       uint64                            `db:"amount"`
	Duration     limesresources.CommitmentDuration `db:"duration"`
	CreatedAt    time.Time                         `db:"created_at"`
	CreatorUUID  string                            `db:"creator_uuid"` // format: "username@userdomainname"
	CreatorName  string                            `db:"creator_name"`
	ConfirmBy    *time.Time                        `db:"confirm_by"`
	ConfirmedAt  *time.Time                        `db:"confirmed_at"`
	ExpiresAt    time.Time                         `db:"expires_at"`

	// A commitment can be superseded e.g. by splitting it into smaller parts.
	// When that happens, the new commitments will point to the one that they
	// superseded through the PredecessorID field.
	SupersededAt  *time.Time           `db:"superseded_at"`
	PredecessorID *ProjectCommitmentID `db:"predecessor_id"`

	// For a commitment to be transferred between projects, it must first be
	// marked for transfer in the source project. Then a new commitment can be
	// created in the target project to supersede the transferable commitment.
	//
	// While a commitment is marked for transfer, it does not count towards quota
	// calculation, but it still blocks capacity and still counts towards billing.
	TransferStatus limesresources.CommitmentTransferStatus `db:"transfer_status"`
	TransferToken  string                                  `db:"transfer_token"`

	// This column is technically redundant, since the state can be derived from
	// the values of other fields. But having this field simplifies lots of
	// queries significantly because we do not need to carry a NOW() argument into
	// the query, and complex conditions like `WHERE superseded_at IS NULL AND
	// expires_at > $now AND confirmed_at IS NULL AND confirm_by < $now` become
	// simple readable conditions like `WHERE state = 'pending'`.
	//
	// This field is updated by the CapacityScrapeJob.
	State CommitmentState `db:"state"`
}

ProjectCommitment contains a record from the `project_commitments` table.

type ProjectCommitmentID

type ProjectCommitmentID int64

ProjectCommitmentID is an ID into the project_commitments table. This typedef is used to distinguish these IDs from IDs of other tables or raw int64 values.

type ProjectID

type ProjectID int64

ProjectID is an ID into the projects table. This typedef is used to distinguish these IDs from IDs of other tables or raw int64 values.

type ProjectRate

type ProjectRate struct {
	ServiceID     ProjectServiceID    `db:"service_id"`
	Name          limesrates.RateName `db:"name"`
	Limit         *uint64             `db:"rate_limit"`      // nil for rates that don't have a limit (just a usage)
	Window        *limesrates.Window  `db:"window_ns"`       // nil for rates that don't have a limit (just a usage)
	UsageAsBigint string              `db:"usage_as_bigint"` // empty for rates that don't have a usage (just a limit)

}

ProjectRate contains a record from the `project_rates` table.

type ProjectResource

type ProjectResource struct {
	ID                      ProjectResourceID           `db:"id"`
	ServiceID               ProjectServiceID            `db:"service_id"`
	Name                    limesresources.ResourceName `db:"name"`
	Quota                   *uint64                     `db:"quota"`
	BackendQuota            *int64                      `db:"backend_quota"`
	MinQuotaFromBackend     *uint64                     `db:"min_quota_from_backend"`
	MaxQuotaFromBackend     *uint64                     `db:"max_quota_from_backend"`
	MaxQuotaFromAdmin       *uint64                     `db:"max_quota_from_admin"`
	OverrideQuotaFromConfig *uint64                     `db:"override_quota_from_config"`
}

ProjectResource contains a record from the `project_resources` table. Quota values are NULL for resources that do not track quota.

func (ProjectResource) Ref

Ref returns the ResourceRef for this resource.

type ProjectResourceID

type ProjectResourceID int64

ProjectResourceID is an ID into the project_resources table. This typedef is used to distinguish these IDs from IDs of other tables or raw int64 values.

type ProjectService

type ProjectService struct {
	ID                      ProjectServiceID  `db:"id"`
	ProjectID               ProjectID         `db:"project_id"`
	Type                    limes.ServiceType `db:"type"`
	ScrapedAt               *time.Time        `db:"scraped_at"` // pointer type to allow for NULL value
	CheckedAt               *time.Time        `db:"checked_at"`
	NextScrapeAt            time.Time         `db:"next_scrape_at"`
	Stale                   bool              `db:"stale"`
	ScrapeDurationSecs      float64           `db:"scrape_duration_secs"`
	ScrapeErrorMessage      string            `db:"scrape_error_message"`
	RatesScrapedAt          *time.Time        `db:"rates_scraped_at"` // same as above
	RatesCheckedAt          *time.Time        `db:"rates_checked_at"`
	RatesNextScrapeAt       time.Time         `db:"rates_next_scrape_at"`
	RatesStale              bool              `db:"rates_stale"`
	RatesScrapeDurationSecs float64           `db:"rates_scrape_duration_secs"`
	RatesScrapeState        string            `db:"rates_scrape_state"`
	RatesScrapeErrorMessage string            `db:"rates_scrape_error_message"`
	SerializedMetrics       string            `db:"serialized_metrics"`
	QuotaDesyncedAt         *time.Time        `db:"quota_desynced_at"`
	QuotaSyncDurationSecs   float64           `db:"quota_sync_duration_secs"`
}

ProjectService contains a record from the `project_services` table.

func (ProjectService) Ref

Ref converts a ProjectService into its ProjectServiceRef.

type ProjectServiceID

type ProjectServiceID int64

ProjectServiceID is an ID into the project_services table. This typedef is used to distinguish these IDs from IDs of other tables or raw int64 values.

type ResourceRef

type ResourceRef[I ~int64] struct {
	ServiceID I                           `db:"service_id"`
	Name      limesresources.ResourceName `db:"name"`
}

ResourceRef identifies an individual ProjectResource, DomainResource or ClusterResource.

type ServiceRef

type ServiceRef[I ~int64] struct {
	ID   I
	Type limes.ServiceType
}

ServiceRef identifies an individual ProjectService, DomainService or ClusterService. It appears in APIs when not the entire Service record is needed.

type SetUpdate

type SetUpdate[R any, K comparable] struct {
	// All relevant records that currently exist in the DB.
	ExistingRecords []R
	// All keys for which we want to have a record in the DB.
	WantedKeys []K

	// KeyForRecord reads the key out of an existing record.
	// This does not need to be the primary key.
	// Whatever unique identifier the caller has available is fine.
	KeyForRecord func(R) K

	// Callback for creating a new record for a missing key.
	//
	// After this, the Update callback will also be called on the new record.
	// This avoids code duplication between the create and update callbacks.
	Create func(K) (R, error)
	// Callback for updating an existing record.
	Update func(*R) error
}

SetUpdate describes an operation where we have an existing set of records (type R), and a set of records that we want to have, as identified by some key (type K). Records that we want to keep are updated, missing records are created, and existing records that we do not want to have are deleted.

TODO This is not yet used in most of the places that could benefit from it.

func (SetUpdate[R, K]) Execute

func (u SetUpdate[R, K]) Execute(tx *gorp.Transaction) ([]R, error)

Execute executes this SetUpdate. Returns the set of records that exist in the DB after this update.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL