sqlcommon

package
v1.11.1 Latest Latest
Warning

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

Go to latest
Published: Nov 20, 2025 License: Apache-2.0 Imports: 22 Imported by: 2

Documentation

Overview

Package sqlcommon contains utility functions shared among all SQL data stores.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func AddFromUlid added in v1.8.0

func AddFromUlid(sb sq.SelectBuilder, fromUlid string, sortDescending bool) sq.SelectBuilder

func BuildRowConstructorIN added in v1.10.4

func BuildRowConstructorIN(keys []TupleLockKey) (string, []interface{})

BuildRowConstructorIN builds "((?,?,?,?,?),(?,?,?,?,?),...)" and arg list for row-constructor IN.

func ConstructAuthorizationModelFromSQLRows added in v1.10.4

func ConstructAuthorizationModelFromSQLRows(rows Rows) (*openfgav1.AuthorizationModel, error)

ConstructAuthorizationModelFromSQLRows tries first to read and return a model that was written in one row (the new format). If it can't find one, it will then look for a model that was written across multiple rows (the old format).

func FindLatestAuthorizationModel added in v1.5.0

func FindLatestAuthorizationModel(
	ctx context.Context,
	dbInfo *DBInfo,
	store string,
) (*openfgav1.AuthorizationModel, error)

FindLatestAuthorizationModel reads the latest authorization model corresponding to the store.

func GetDeleteWriteChangelogItems added in v1.10.4

func GetDeleteWriteChangelogItems(
	store string,
	existing map[string]*openfgav1.Tuple,
	writeData WriteData) (sq.Or, [][]interface{}, [][]interface{}, error)

GetDeleteWriteChangelogItems constructs the delete conditions, write items, and changelog items.

func IsReady added in v1.3.4

func IsReady(ctx context.Context, skipVersionCheck bool, db *sql.DB) (storage.ReadinessStatus, error)

IsReady returns true if connection to datastore is successful AND (the datastore has the latest migration applied OR skipVersionCheck).

func IsVersionReady added in v1.10.4

func IsVersionReady(ctx context.Context, skipVersionCheck bool, db *sql.DB) (storage.ReadinessStatus, error)

IsVersionReady checks if the database schema revision is at least the minimum supported revision. The passed in context should have a timeout.

func MarshalRelationshipCondition added in v1.6.1

func MarshalRelationshipCondition(
	rel *openfgav1.RelationshipCondition,
) (name string, context []byte, err error)

func NewSQLContinuationTokenSerializer added in v1.8.0

func NewSQLContinuationTokenSerializer() encoder.ContinuationTokenSerializer

func ReadAuthorizationModel added in v1.3.3

func ReadAuthorizationModel(
	ctx context.Context,
	dbInfo *DBInfo,
	store, modelID string,
) (*openfgav1.AuthorizationModel, error)

ReadAuthorizationModel reads the model corresponding to store and model ID.

func SQLIteratorColumns added in v1.10.0

func SQLIteratorColumns() []string

SQLIteratorColumns returns the columns used in the SQL tuple iterator.

func Write

func Write(
	ctx context.Context,
	dbInfo *DBInfo,
	db *sql.DB,
	store string,
	writeData WriteData,
) error

Write provides the common method for writing to database across sql storage.

func WriteAuthorizationModel added in v1.3.3

func WriteAuthorizationModel(
	ctx context.Context,
	dbInfo *DBInfo,
	store string,
	model *openfgav1.AuthorizationModel,
) error

WriteAuthorizationModel writes an authorization model for the given store in one row.

Types

type Config

type Config struct {
	SecondaryURI           string
	Username               string
	Password               string
	SecondaryUsername      string
	SecondaryPassword      string
	Logger                 logger.Logger
	MaxTuplesPerWriteField int
	MaxTypesPerModelField  int

	MaxOpenConns    int
	MinOpenConns    int
	MaxIdleConns    int
	MinIdleConns    int
	ConnMaxIdleTime time.Duration
	ConnMaxLifetime time.Duration

	ExportMetrics bool
}

Config defines the configuration parameters for setting up and managing a sql connection.

func NewConfig

func NewConfig(opts ...DatastoreOption) *Config

NewConfig creates a new Config instance with default values and applies any provided DatastoreOption modifications.

type ContToken

type ContToken struct {
	Ulid       string `json:"ulid"`
	ObjectType string `json:"ObjectType"`
}

ContToken represents a continuation token structure used in pagination.

func NewContToken

func NewContToken(ulid, objectType string) *ContToken

NewContToken creates a new instance of ContToken with the provided ULID and object type.

type DBInfo

type DBInfo struct {
	HandleSQLError errorHandlerFn
	// contains filtered or unexported fields
}

DBInfo encapsulates DB information for use in common method.

func NewDBInfo

func NewDBInfo(stbl sq.StatementBuilderType, errorHandler errorHandlerFn, dialect string) *DBInfo

NewDBInfo constructs a DBInfo object.

type DatastoreOption

type DatastoreOption func(*Config)

DatastoreOption defines a function type used for configuring a Config object.

func WithConnMaxIdleTime

func WithConnMaxIdleTime(d time.Duration) DatastoreOption

WithConnMaxIdleTime returns a DatastoreOption that sets the maximum idle time for a connection in the Config.

func WithConnMaxLifetime

func WithConnMaxLifetime(d time.Duration) DatastoreOption

WithConnMaxLifetime returns a DatastoreOption that sets the maximum lifetime for a connection in the Config.

func WithLogger

func WithLogger(l logger.Logger) DatastoreOption

WithLogger returns a DatastoreOption that sets the Logger in the Config.

func WithMaxIdleConns

func WithMaxIdleConns(c int) DatastoreOption

WithMaxIdleConns returns a DatastoreOption that sets the maximum number of idle connections in the Config.

func WithMaxOpenConns

func WithMaxOpenConns(c int) DatastoreOption

WithMaxOpenConns returns a DatastoreOption that sets the maximum number of open connections in the Config.

func WithMaxTuplesPerWrite

func WithMaxTuplesPerWrite(maxTuples int) DatastoreOption

WithMaxTuplesPerWrite returns a DatastoreOption that sets the maximum number of tuples per write in the Config.

func WithMaxTypesPerAuthorizationModel

func WithMaxTypesPerAuthorizationModel(maxTypes int) DatastoreOption

WithMaxTypesPerAuthorizationModel returns a DatastoreOption that sets the maximum number of types per authorization model in the Config.

func WithMetrics added in v1.3.5

func WithMetrics() DatastoreOption

WithMetrics returns a DatastoreOption that enables the export of metrics in the Config.

func WithMinIdleConns added in v1.10.4

func WithMinIdleConns(c int) DatastoreOption

WithMinIdleConns returns a DatastoreOption that sets the minimum number of idle connections in the Config. This is only used by some SQL drivers (e.g., pgxpool that is used in PostgresSQL).

func WithMinOpenConns added in v1.10.4

func WithMinOpenConns(c int) DatastoreOption

WithMinOpenConns returns a DatastoreOption that sets the minimum number of open connections in the Config. This is only used by some SQL drivers (e.g., pgxpool that is used in PostgresSQL).

func WithPassword added in v1.1.0

func WithPassword(password string) DatastoreOption

WithPassword returns a DatastoreOption that sets the password in the Config.

func WithSecondaryPassword added in v1.8.15

func WithSecondaryPassword(password string) DatastoreOption

WithSecondaryPassword returns a DatastoreOption that sets the secondary password in the Config.

func WithSecondaryURI added in v1.8.15

func WithSecondaryURI(uri string) DatastoreOption

WithSecondaryURI returns a DatastoreOption that sets the secondary URI in the Config.

func WithSecondaryUsername added in v1.8.15

func WithSecondaryUsername(username string) DatastoreOption

WithSecondaryUsername returns a DatastoreOption that sets the secondary username in the Config.

func WithUsername added in v1.1.0

func WithUsername(username string) DatastoreOption

WithUsername returns a DatastoreOption that sets the username in the Config.

type Rows added in v1.10.4

type Rows interface {
	Close() error
	Err() error
	Next() bool
	Scan(dest ...any) error
}

Rows is an interface that abstracts the iteration over SQL query results. It provides methods to close the result set, check for errors, advance to the next row, and scan the current row's columns into provided destinations. It is intended as a subset of *sql.Rows to facilitate compatibility with *pgx.Rows as well.

Methods:

  • Close(): Closes the rows iterator and releases any resources.
  • Err(): Returns the error, if any, that was encountered during iteration.
  • Next(): Advances to the next row, returning true if there is another row available.
  • Scan(dest ...any): Scans the columns of the current row into the provided destination variables.

type SBIteratorQuery added in v1.10.4

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

func NewSBIteratorQuery added in v1.10.4

func NewSBIteratorQuery(sb sq.SelectBuilder) *SBIteratorQuery

func (*SBIteratorQuery) GetRows added in v1.10.4

func (q *SBIteratorQuery) GetRows(ctx context.Context) (Rows, error)

type SQLContinuationTokenSerializer added in v1.8.0

type SQLContinuationTokenSerializer struct{}

func (*SQLContinuationTokenSerializer) Deserialize added in v1.8.0

func (s *SQLContinuationTokenSerializer) Deserialize(continuationToken string) (ulid string, objType string, err error)

func (*SQLContinuationTokenSerializer) Serialize added in v1.8.0

func (s *SQLContinuationTokenSerializer) Serialize(ulid string, objType string) ([]byte, error)

type SQLIteratorRowGetter added in v1.10.4

type SQLIteratorRowGetter interface {
	GetRows(context.Context) (Rows, error)
}

SQLIteratorRowGetter is an interface for retrieving rows from a SQL query. Implementations should provide the GetRows method, which executes a query and returns a Rows object for iteration.

GetRows executes the query and returns the resulting Rows or an error.

type SQLTupleIterator

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

SQLTupleIterator is a struct that implements the storage.TupleIterator interface for iterating over tuples fetched from a SQL database.

func NewSQLTupleIterator

func NewSQLTupleIterator(rowGetter SQLIteratorRowGetter, errHandler errorHandlerFn) *SQLTupleIterator

NewSQLTupleIterator returns a SQL tuple iterator.

func (*SQLTupleIterator) Head added in v1.5.9

Head will return the first available item.

func (*SQLTupleIterator) Next

Next will return the next available item.

func (*SQLTupleIterator) Stop

func (t *SQLTupleIterator) Stop()

Stop terminates iteration.

func (*SQLTupleIterator) ToArray

ToArray converts the tupleIterator to an []*openfgav1.Tuple and a possibly empty continuation token. If the continuation token exists it is the ulid of the last element of the returned array.

type TupleLockKey added in v1.10.4

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

TupleLockKey represents the composite key we lock on.

func MakeTupleLockKeys added in v1.10.4

func MakeTupleLockKeys(deletes storage.Deletes, writes storage.Writes) []TupleLockKey

MakeTupleLockKeys flattens Deletes+writes into a deduped, sorted slice to ensure stable lock order.

type WriteData added in v1.10.4

type WriteData struct {
	Deletes storage.Deletes
	Writes  storage.Writes
	Opts    storage.TupleWriteOptions
	Now     time.Time
}

Jump to

Keyboard shortcuts

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