db

package
v0.11.6 Latest Latest
Warning

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

Go to latest
Published: Nov 19, 2025 License: BSD-3-Clause-Clear Imports: 26 Imported by: 0

Documentation

Index

Constants

View Source
const (
	ErrTextCreationFailed               = "resource creation failed"
	ErrTextDeletionFailed               = "resource deletion failed"
	ErrTextDeactivationFailed           = "resource deactivation failed"
	ErrTextGetRetrievalFailed           = "resource retrieval failed"
	ErrTextListRetrievalFailed          = "resource list retrieval failed"
	ErrTextUpdateFailed                 = "resource update failed"
	ErrTextNotFound                     = "resource not found"
	ErrTextConflict                     = "resource unique field violation"
	ErrTextRelationInvalid              = "resource relation invalid"
	ErrTextEnumValueInvalid             = "enum value invalid"
	ErrTextUUIDInvalid                  = "invalid input syntax for type uuid"
	ErrTextRestrictViolation            = "intended action would violate a restriction"
	ErrTextFqnMissingValue              = "FQN must specify a valid value and be of format 'https://<namespace>/attr/<attribute name>/value/<value>'"
	ErrTextListLimitTooLarge            = "requested pagination limit must be less than or equal to configured limit"
	ErrTextInvalidIdentifier            = "value sepcified as the identifier is invalid"
	ErrorTextUnknownIdentifier          = "could not match identifier to known type"
	ErrorTextUpdateToUnspecified        = "cannot update to unspecified value"
	ErrTextKeyRotationFailed            = "key rotation failed"
	ErrorTextExpectedBase64EncodedValue = "expected base64 encoded value"
	ErrorTextMarshalFailed              = "failed to marshal value"
	ErrorTextUnmarsalFailed             = "failed to unmarshal value"
	ErrorTextNamespaceMismatch          = "namespace mismatch"
	ErrorTextKasURIMismatch             = "kas uri mismatch"
	ErrorTextKIDMismatch                = "key id mismatch"
	ErrorTextInvalidOblTrigParam        = "either the obligation value, attribute value, or action provided is invalid"
	ErrorTextFqnMismatch                = "fqn mismatch"
	ErrorTextInvalidCertificate         = "invalid certificate"
)

Variables

View Source
var (
	ErrUniqueConstraintViolation  = errors.New("ErrUniqueConstraintViolation: value must be unique")
	ErrNotNullViolation           = errors.New("ErrNotNullViolation: value cannot be null")
	ErrForeignKeyViolation        = errors.New("ErrForeignKeyViolation: value is referenced by another table")
	ErrRestrictViolation          = errors.New("ErrRestrictViolation: value cannot be deleted due to restriction")
	ErrNotFound                   = errors.New("ErrNotFound: value not found")
	ErrEnumValueInvalid           = errors.New("ErrEnumValueInvalid: not a valid enum value")
	ErrUUIDInvalid                = errors.New("ErrUUIDInvalid: value not a valid UUID")
	ErrMissingValue               = errors.New("ErrMissingValue: value must be included")
	ErrListLimitTooLarge          = errors.New("ErrListLimitTooLarge: requested limit greater than configured maximum")
	ErrTxBeginFailed              = errors.New("ErrTxBeginFailed: failed to begin DB transaction")
	ErrTxRollbackFailed           = errors.New("ErrTxRollbackFailed: failed to rollback DB transaction")
	ErrTxCommitFailed             = errors.New("ErrTxCommitFailed: failed to commit DB transaction")
	ErrSelectIdentifierInvalid    = errors.New("ErrSelectIdentifierInvalid: invalid identifier value for select query")
	ErrUnknownSelectIdentifier    = errors.New("ErrUnknownSelectIdentifier: unknown identifier type for select query")
	ErrCannotUpdateToUnspecified  = errors.New("ErrCannotUpdateToUnspecified: cannot update to unspecified value")
	ErrKeyRotationFailed          = errors.New("ErrTextKeyRotationFailed: key rotation failed")
	ErrExpectedBase64EncodedValue = errors.New("ErrExpectedBase64EncodedValue: expected base64 encoded value")
	ErrMarshalValueFailed         = errors.New("ErrMashalValueFailed: failed to marshal value")
	ErrUnmarshalValueFailed       = errors.New("ErrUnmarshalValueFailed: failed to unmarshal value")
	ErrNamespaceMismatch          = errors.New("ErrNamespaceMismatch: namespace mismatch")
	ErrKIDMismatch                = errors.New("ErrKIDMismatch: Key ID mismatch")
	ErrKasURIMismatch             = errors.New("ErrKasURIMismatch: KAS URI mismatch")
	ErrInvalidOblTriParam         = errors.New("ErrInvalidOblTriParam: either the obligation value, attribute value, or action provided was not found")
	ErrCheckViolation             = errors.New("ErrCheckViolation: check constraint violation")
	ErrFqnMismatch                = errors.New("ErrFqnMismatch: FQN mismatch")
	ErrInvalidCertificate         = errors.New("ErrInvalidCertificate: invalid certificate")
)

Functions

func CertificatesProtoJSON added in v0.11.0

func CertificatesProtoJSON(certsJSON []byte) ([]*policy.Certificate, error)

func FormatAlg added in v0.6.0

func FormatAlg(alg policy.Algorithm) (string, error)

func GrantedPolicyObjectProtoJSON added in v0.4.19

func GrantedPolicyObjectProtoJSON(grantsJSON []byte) ([]*kasregistry.GrantedPolicyObject, error)

func IsQueryBuilderSetClauseError

func IsQueryBuilderSetClauseError(err error) bool

func KasKeysProtoJSON added in v0.5.3

func KasKeysProtoJSON(keysJSON []byte) ([]*policy.KasKey, error)

func KeyAccessServerProtoJSON

func KeyAccessServerProtoJSON(keyAccessServerJSON []byte) ([]*policy.KeyAccessServer, error)

func MappedPolicyObjectProtoJSON added in v0.8.0

func MappedPolicyObjectProtoJSON(mappingsJSON []byte) ([]*kasregistry.MappedPolicyObject, error)

func MarshalCreateMetadata

func MarshalCreateMetadata(metadata *common.MetadataMutable) ([]byte, *common.Metadata, error)

func MarshalUpdateMetadata

func MarshalUpdateMetadata(m *common.MetadataMutable, b common.MetadataUpdateEnum, getExtendableMetadata func() (*common.Metadata, error)) ([]byte, *common.Metadata, error)

func NewStatementBuilder

func NewStatementBuilder() sq.StatementBuilderType

Postgres uses $1, $2, etc. for placeholders

func NewTable

func NewTable(schema string) func(name string) Table

func NewUniqueAlreadyExistsError

func NewUniqueAlreadyExistsError(value string) error

func SimpleKasKeysProtoJSON added in v0.6.0

func SimpleKasKeysProtoJSON(keysJSON []byte) ([]*policy.SimpleKasKey, error)

func StatusifyError

func StatusifyError(ctx context.Context, l *logger.Logger, err error, fallbackErr string, logs ...any) error

func UnmarshalCertificate added in v0.11.0

func UnmarshalCertificate(certJSON []byte) (*policy.Certificate, error)

func UnmarshalSimpleKasKey added in v0.5.4

func UnmarshalSimpleKasKey(keysJSON []byte) (*policy.SimpleKasKey, error)

func WrapIfKnownInvalidQueryErr

func WrapIfKnownInvalidQueryErr(err error) error

Get helpful error message for PostgreSQL violation

Types

type Client

type Client struct {
	Pgx    PgxIface
	Logger *logger.Logger

	// This is the stdlib connection that is used for transactions
	SQLDB *sql.DB
	trace.Tracer
	// contains filtered or unexported fields
}

A wrapper around a pgxpool.Pool and sql.DB reference.

Each service should have a single instance of the Client to share a connection pool, schema (driven by the service namespace), and an embedded file system for migrations.

The 'search_path' is set to the schema on connection to the database.

If the database config 'runMigrations' is set to true, the client will run migrations on startup, once per namespace (as there should only be one embedded migrations FS per namespace).

Multiple pools, schemas, or migrations per service are not supported. Multiple databases per PostgreSQL instance or multiple PostgreSQL servers per platform instance are not supported.

func New

func New(ctx context.Context, config Config, logCfg logger.Config, tracer *trace.Tracer, o ...OptsFunc) (*Client, error)

Connections and pools seems to be pulled in from env vars We should be able to tell the platform how to run

func (*Client) Close

func (c *Client) Close()

func (Client) Exec

func (c Client) Exec(ctx context.Context, sql string, args []interface{}) error

Common function for all exec calls

func (*Client) MigrationDown

func (c *Client) MigrationDown(ctx context.Context, migrations *embed.FS) error

func (*Client) MigrationStatus

func (c *Client) MigrationStatus(ctx context.Context) ([]*goose.MigrationStatus, error)

func (*Client) MigrationsEnabled added in v0.4.18

func (c *Client) MigrationsEnabled() bool

func (Client) Query

func (c Client) Query(ctx context.Context, sql string, args []interface{}) (pgx.Rows, error)

Common function for all query calls

func (Client) QueryRow

func (c Client) QueryRow(ctx context.Context, sql string, args []interface{}) (pgx.Row, error)

Common function for all queryRow calls

func (*Client) RanMigrations added in v0.4.18

func (c *Client) RanMigrations() bool

func (*Client) RunMigrations

func (c *Client) RunMigrations(ctx context.Context, migrations *embed.FS) (int, error)

RunMigrations runs the migrations for the schema Schema will be created if it doesn't exist

func (*Client) Schema

func (c *Client) Schema() string

type Config

type Config struct {
	Host           string     `mapstructure:"host" json:"host" default:"localhost"`
	Port           int        `mapstructure:"port" json:"port" default:"5432"`
	Database       string     `mapstructure:"database" json:"database" default:"opentdf"`
	User           string     `mapstructure:"user" json:"user" default:"postgres"`
	Password       string     `mapstructure:"password" json:"password" default:"changeme"`
	SSLMode        string     `mapstructure:"sslmode" json:"sslmode" default:"prefer"`
	Schema         string     `mapstructure:"schema" json:"schema" default:"opentdf"`
	ConnectTimeout int        `mapstructure:"connect_timeout_seconds" json:"connect_timeout_seconds" default:"15"`
	Pool           PoolConfig `mapstructure:"pool" json:"pool"`

	RunMigrations    bool      `mapstructure:"runMigrations" json:"runMigrations" default:"true"`
	MigrationsFS     *embed.FS `mapstructure:"-" json:"-"`
	VerifyConnection bool      `mapstructure:"verifyConnection" json:"verifyConnection" default:"true"`
}

func (Config) LogValue added in v0.4.19

func (c Config) LogValue() slog.Value

type OptsFunc

type OptsFunc func(c Config) Config

func WithMigrations

func WithMigrations(fs *embed.FS) OptsFunc

func WithService

func WithService(name string) OptsFunc

type PgxIface

type PgxIface interface {
	Acquire(ctx context.Context) (*pgxpool.Conn, error)
	Begin(ctx context.Context) (pgx.Tx, error)
	Exec(context.Context, string, ...any) (pgconn.CommandTag, error)
	QueryRow(context.Context, string, ...any) pgx.Row
	Query(context.Context, string, ...any) (pgx.Rows, error)
	Ping(context.Context) error
	Close()
	Config() *pgxpool.Config
	CopyFrom(ctx context.Context, tableName pgx.Identifier, columnNames []string, rowSrc pgx.CopyFromSource) (int64, error)
}

We can rename this but wanted to get mocks working.

type PoolConfig added in v0.5.3

type PoolConfig struct {
	// Maximum amount of connections to keep in the pool.
	MaxConns int32 `mapstructure:"max_connection_count" json:"max_connection_count" default:"4"`

	// Minimum amount of connections to keep in the pool.
	MinConns int32 `mapstructure:"min_connection_count" json:"min_connection_count" default:"0"`

	// Minimum amount of idle connections to keep in the pool.
	MinIdleConns int32 `mapstructure:"min_idle_connections_count" json:"min_idle_connections_count" default:"0"`

	// Maximum amount of time a connection may be reused, in seconds. Default: 3600 seconds (1 hour).
	MaxConnLifetime int `mapstructure:"max_connection_lifetime_seconds" json:"max_connection_lifetime_seconds" default:"3600"`

	// Maximum amount of time a connection may be idle before being closed, in seconds. Default: 1800 seconds (30 minutes).
	MaxConnIdleTime int `mapstructure:"max_connection_idle_seconds" json:"max_connection_idle_seconds" default:"1800"`

	// Period at which the pool will check the health of idle connections, in seconds. Default: 60 seconds (1 minute).
	HealthCheckPeriod int `mapstructure:"health_check_period_seconds" json:"health_check_period_seconds" default:"60"`
}

PoolConfig holds all connection pool related configuration

type Table

type Table struct {
	// contains filtered or unexported fields
}

func (Table) Field

func (t Table) Field(field string) string

func (Table) Name

func (t Table) Name() string

func (Table) WithoutSchema

func (t Table) WithoutSchema() Table

Jump to

Keyboard shortcuts

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