pgdb

package
v1.4.0 Latest Latest
Warning

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

Go to latest
Published: Jun 19, 2023 License: Apache-2.0 Imports: 38 Imported by: 0

Documentation

Overview

Package pgdb provides PostgreSQL connection utilities.

Index

Constants

This section is empty.

Variables

View Source
var (
	// ErrTableNotExist indicates that there is no such table.
	ErrTableNotExist = fmt.Errorf("collection/table does not exist")

	// ErrSchemaNotExist indicates that there is no such schema.
	ErrSchemaNotExist = fmt.Errorf("database/schema does not exist")

	// ErrAlreadyExist indicates that a schema or table already exists.
	ErrAlreadyExist = fmt.Errorf("database/schema or collection/table already exists")

	// ErrIndexKeyAlreadyExist indicates that an index key already exists with a different name.
	ErrIndexKeyAlreadyExist = fmt.Errorf("index key already exists with a different name")

	// ErrIndexNameAlreadyExist indicates that an index name already exists with a different key.
	ErrIndexNameAlreadyExist = fmt.Errorf("index name already exists with a different key")

	// ErrIndexNotExist indicates there is no such index.
	ErrIndexNotExist = fmt.Errorf("index does not exist")

	// ErrIndexCannotDelete indicates the index cannot be deleted.
	ErrIndexCannotDelete = fmt.Errorf("index cannot be deleted")

	// ErrInvalidCollectionName indicates that a collection didn't pass name checks.
	ErrInvalidCollectionName = fmt.Errorf("invalid FerretDB collection name")

	// ErrInvalidDatabaseName indicates that a database didn't pass name checks.
	ErrInvalidDatabaseName = fmt.Errorf("invalid FerretDB database name")

	// ErrUniqueViolation indicates that operations violates a unique constraint.
	ErrUniqueViolation = fmt.Errorf("unique constraint violation")
)

Errors are wrapped with lazyerrors.Error, so the caller needs to use errors.Is to check the error, for example, errors.Is(err, ErrSchemaNotExist).

Functions

func CollectionExists added in v0.5.1

func CollectionExists(ctx context.Context, tx pgx.Tx, db, collection string) (bool, error)

CollectionExists returns true if FerretDB collection exists.

func Collections added in v0.5.1

func Collections(ctx context.Context, tx pgx.Tx, db string) ([]string, error)

Collections returns a sorted list of FerretDB collection names.

It returns (possibly wrapped) ErrSchemaNotExist if FerretDB database / PostgreSQL schema does not exist.

func CreateCollection added in v0.5.1

func CreateCollection(ctx context.Context, tx pgx.Tx, db, collection string) error

CreateCollection creates a new FerretDB collection with the given name in the given database. If the database does not exist, it will be created. It also creates a unique index on the _id field.

It returns possibly wrapped error:

  • ErrInvalidDatabaseName - if the given database name doesn't conform to restrictions.
  • ErrInvalidCollectionName - if the given collection name doesn't conform to restrictions.
  • ErrAlreadyExist - if a FerretDB collection with the given name already exists.
  • *transactionConflictError - if a PostgreSQL conflict occurs (the caller could retry the transaction).

func CreateCollectionIfNotExists added in v0.8.0

func CreateCollectionIfNotExists(ctx context.Context, tx pgx.Tx, db, collection string) error

CreateCollectionIfNotExists ensures that given FerretDB database and collection exist. If the database does not exist, it will be created.

It returns possibly wrapped error:

  • ErrInvalidDatabaseName - if the given database name doesn't conform to restrictions.
  • ErrInvalidCollectionName - if the given collection name doesn't conform to restrictions.
  • *transactionConflictError - if a PostgreSQL conflict occurs (the caller could retry the transaction).

func CreateDatabaseIfNotExists added in v0.5.1

func CreateDatabaseIfNotExists(ctx context.Context, tx pgx.Tx, db string) error

CreateDatabaseIfNotExists creates a new FerretDB database (PostgreSQL schema).

If a PostgreSQL conflict occurs it returns *transactionConflictError, and the caller could retry the transaction.

func CreateIndexIfNotExists added in v1.0.0

func CreateIndexIfNotExists(ctx context.Context, tx pgx.Tx, db, collection string, i *Index) error

CreateIndexIfNotExists creates a new index for the given params if such an index doesn't exist.

If the index exists, it doesn't return an error. If the collection doesn't exist, it will be created and then the index will be created.

func DatabaseSize added in v0.7.0

func DatabaseSize(ctx context.Context, tx pgx.Tx) (int64, error)

DatabaseSize returns the size of the current database in bytes.

func Databases added in v0.5.1

func Databases(ctx context.Context, tx pgx.Tx) ([]string, error)

Databases returns a sorted list of FerretDB databases / PostgreSQL schemas.

func DeleteDocumentsByID added in v0.5.3

func DeleteDocumentsByID(ctx context.Context, tx pgx.Tx, qp *QueryParams, ids []any) (int64, error)

DeleteDocumentsByID deletes documents by given IDs.

func DropAllIndexes added in v1.0.0

func DropAllIndexes(ctx context.Context, tx pgx.Tx, db, collection string) (int32, error)

DropAllIndexes deletes all indexes on the collection except _id index.

func DropCollection added in v0.5.1

func DropCollection(ctx context.Context, tx pgx.Tx, db, collection string) error

DropCollection drops FerretDB collection.

It returns (possibly wrapped) ErrTableNotExist if database or collection does not exist. Please use errors.Is to check the error.

TODO Test correctness for concurrent cases https://github.com/FerretDB/FerretDB/issues/1684

func DropDatabase added in v0.5.3

func DropDatabase(ctx context.Context, tx pgx.Tx, db string) (err error)

DropDatabase drops FerretDB database.

func DropIndex added in v1.0.0

func DropIndex(ctx context.Context, tx pgx.Tx, db, collection string, index *Index) (int32, error)

DropIndex drops index. If the index was not found, it returns error.

func InsertDocument added in v0.5.1

func InsertDocument(ctx context.Context, tx pgx.Tx, db, collection string, doc *types.Document) error

InsertDocument inserts a document into FerretDB database and collection. If database or collection does not exist, it will be created.

It returns possibly wrapped error:

  • *types.ValidationError - if the document is not valid.
  • ErrUniqueViolation - if pgerrcode.UniqueViolation error is caught (e.g. due to unique index constraint).
  • ErrInvalidCollectionName - if the given collection name doesn't conform to restrictions.
  • ErrInvalidDatabaseName - if the given database name doesn't conform to restrictions.
  • *transactionConflictError - if a PostgreSQL conflict occurs (the caller could retry the transaction).

func RenameCollection added in v1.1.0

func RenameCollection(ctx context.Context, tx pgx.Tx, db, collectionFrom, collectionTo string) error

RenameCollection changes the name of an existing collection.

It returns ErrTableNotExist if either source database or collection does not exist. It returns ErrAlreadyExist if the target database or collection already exists. It returns ErrInvalidCollectionName if collection name is not valid.

func SetDocumentByID added in v0.5.3

func SetDocumentByID(ctx context.Context, tx pgx.Tx, qp *QueryParams, id any, doc *types.Document) (int64, error)

SetDocumentByID sets a document by its ID. If the document is not valid, it returns *types.ValidationError.

Types

type CollStats added in v1.1.0

type CollStats struct {
	CountObjects   int64
	CountIndexes   int64
	SizeTotal      int64
	SizeIndexes    int64
	SizeCollection int64
}

CollStats describes statistics for a FerretDB collection (PostgreSQL table).

MongoDB uses "numbers" for those values that could be int32 or int64. FerretDB always returns int64 for simplicity.

TODO Include more data https://github.com/FerretDB/FerretDB/issues/2447.

func CalculateCollStats added in v1.1.0

func CalculateCollStats(ctx context.Context, tx pgx.Tx, db, collection string) (*CollStats, error)

CalculateCollStats returns statistics for the given FerretDB collection in the given database.

If the collection does not exist, it returns an object filled with zeros for all the fields.

type DBStats

type DBStats struct {
	CountCollections int64
	CountObjects     int64
	CountIndexes     int64
	SizeTotal        int64
	SizeIndexes      int64
	SizeCollections  int64
}

DBStats describes statistics for a FerretDB database (PostgreSQL schema).

MongoDB uses "numbers" for those values that could be int32 or int64. FerretDB always returns int64 for simplicity.

TODO Include more data https://github.com/FerretDB/FerretDB/issues/2447.

func CalculateDBStats added in v1.1.0

func CalculateDBStats(ctx context.Context, tx pgx.Tx, db string) (*DBStats, error)

CalculateDBStats returns statistics for the given FerretDB database.

If the database does not exist, it returns an object filled with zeros for all the fields.

type FetchedDocs added in v0.5.1

type FetchedDocs struct {
	Docs []*types.Document
	Err  error
}

FetchedDocs is a struct that contains a list of documents and an error. It is used in the fetched channel returned by QueryDocuments.

type Index added in v0.9.4

type Index struct {
	Name   string
	Key    IndexKey
	Unique *bool // we have to use pointer to determine whether the field was set or not
}

Index contains user-visible properties of FerretDB index.

func Indexes added in v0.9.4

func Indexes(ctx context.Context, tx pgx.Tx, db, collection string) ([]Index, error)

Indexes returns a list of indexes for the given database and collection.

If the given collection does not exist, it returns ErrTableNotExist.

type IndexKey added in v0.9.4

type IndexKey []IndexKeyPair

IndexKey is a list of field name + sort order pairs.

func (IndexKey) Equal added in v1.0.0

func (k IndexKey) Equal(v IndexKey) bool

Equal returns true if the given index key is equal to the current one.

type IndexKeyPair added in v0.9.4

type IndexKeyPair struct {
	Field string
	Order types.SortType
}

IndexKeyPair consists of a field name and a sort order that are part of the index.

type Placeholder

type Placeholder int

Placeholder stores the number of the relevant placeholder of the query.

func (*Placeholder) Next

func (p *Placeholder) Next() string

Next increases the identifier value for the next variable in the PostgreSQL query.

type Pool

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

Pool represents PostgreSQL concurrency-safe connection pool.

func NewPool

func NewPool(ctx context.Context, uri string, logger *zap.Logger, p *state.Provider) (*Pool, error)

NewPool returns a new concurrency-safe connection pool.

Passed context is used only by the first checking connection. Canceling it after that function returns does nothing.

func (*Pool) Close added in v1.0.0

func (pgPool *Pool) Close()

Close closes all connections in the pool.

It blocks until all connections are closed.

func (*Pool) InTransaction added in v0.5.1

func (pgPool *Pool) InTransaction(ctx context.Context, f func(pgx.Tx) error) (err error)

InTransaction wraps the given function f in a transaction.

If f returns an error, the transaction is rolled back.

Passed context will be used for BEGIN/ROLLBACK/COMMIT statements. Context cancellation does not rollback the transaction. In practice, f should use the same ctx for Query/QueryRow/Exec that would return an error if context is canceled.

Errors are wrapped with lazyerrors.Error, so the caller needs to use errors.Is to check the error, for example, errors.Is(err, ErrSchemaNotExist).

func (*Pool) InTransactionRetry added in v0.8.0

func (pgPool *Pool) InTransactionRetry(ctx context.Context, f func(pgx.Tx) error) error

InTransactionRetry wraps the given function f in a transaction. If f returns (possibly wrapped) *transactionConflictError, the transaction is retried multiple times with delays. If the transaction still fails after that, the last error is returned.

func (*Pool) TablesSize added in v0.7.0

func (pgPool *Pool) TablesSize(ctx context.Context, tx pgx.Tx, db string) (int64, error)

TablesSize returns the sum of sizes of all tables in the given database in bytes.

type QueryParams added in v0.9.2

type QueryParams struct {
	// Query filter for possible pushdown; may be ignored in part or entirely.
	Filter     *types.Document
	Sort       *types.Document
	DB         string
	Collection string
	Comment    string
	Explain    bool
}

QueryParams represents options/parameters used for SQL query.

type QueryResults added in v1.1.0

type QueryResults struct {
	FilterPushdown bool
	SortPushdown   bool
}

QueryResults represents operations that were done by query builder.

func Explain added in v0.5.3

func Explain(ctx context.Context, tx pgx.Tx, qp *QueryParams) (*types.Document, QueryResults, error)

Explain returns SQL EXPLAIN results for given query parameters.

It returns (possibly wrapped) ErrTableNotExist if database or collection does not exist.

func QueryDocuments added in v0.9.2

func QueryDocuments(ctx context.Context, tx pgx.Tx, qp *QueryParams) (types.DocumentsIterator, QueryResults, error)

QueryDocuments returns an queryIterator to fetch documents for given SQLParams. If the collection doesn't exist, it returns an empty iterator and no error. If an error occurs, it returns nil and that error, possibly wrapped.

Transaction is not closed by this function. Use iterator.WithClose if needed.

type ServerStats added in v1.1.0

type ServerStats struct {
	CountCollections int32
}

ServerStats describes statistics for all the FerretDB databases.

func CalculateServerStats added in v1.1.0

func CalculateServerStats(ctx context.Context, tx pgx.Tx) (*ServerStats, error)

CalculateServerStats returns statistics for all the FerretDB databases on the server.

Jump to

Keyboard shortcuts

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