db

package
v0.0.0-...-54d0854 Latest Latest
Warning

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

Go to latest
Published: Feb 14, 2024 License: Apache-2.0 Imports: 41 Imported by: 0

Documentation

Index

Constants

View Source
const (
	MockRowsAffected = int64(999)
	MockLastInsertID = int64(111)
	MockEncryptorKey = "e286d76de2378ce776389a4f6df2b112"
)
View Source
const KeyLength = 32

Variables

View Source
var DefaultMigrationConfig = MigrationConfig(DefaultMigrations())

DefaultMigrationConfig is a shortcut to the default migrations defined in the config repository

View Source
var (
	DefaultSharedContainerSettings = &PostgresContainerSettings{
		"default-db-shared",
		"postgres:11-alpine",
		DefaultMigrationConfig,
		"127.0.0.1",
		"kyma",
		5432,
		"kyma",
		"kyma",
		"disable",
		"",
		UnittestEncryptionKeyFileConfig,
	}
)
View Source
var UnittestEncryptionKeyFileConfig = EncryptionKeyFileConfig(UnittestEncryptionKeyFile())

UnittestEncryptionKeyFileConfig is a shortcut to the default unit test key

Functions

func DefaultMigrations

func DefaultMigrations() string

func IsInvalidEntityError

func IsInvalidEntityError(err error) bool

func MigrateDatabase

func MigrateDatabase(configFile string, debug bool) error

func NewEncryptionKey

func NewEncryptionKey() (string, error)

NewEncryptionKey generates a random 32 byte key for AES-256

func Transaction

func Transaction(conn Connection, dbOps func(tx *TxConnection) error, logger *zap.SugaredLogger) error

func TransactionResult

func TransactionResult(conn Connection, dbOps func(tx *TxConnection) (interface{}, error),
	logger *zap.SugaredLogger) (interface{}, error)

func UnittestEncryptionKeyFile

func UnittestEncryptionKeyFile() string

Types

type ColumnHandler

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

func NewColumnHandler

func NewColumnHandler(entity DatabaseEntity, conn Connection, logger *zap.SugaredLogger) (*ColumnHandler, error)

func (*ColumnHandler) ColumnEntriesCsv

func (ch *ColumnHandler) ColumnEntriesCsv(onlyWriteable bool) (string, int, error)

func (*ColumnHandler) ColumnEntriesPlaceholderCsv

func (ch *ColumnHandler) ColumnEntriesPlaceholderCsv(onlyWriteable bool) (string, int, error)

func (*ColumnHandler) ColumnName

func (ch *ColumnHandler) ColumnName(field string) (string, error)

func (*ColumnHandler) ColumnNamesCsv

func (ch *ColumnHandler) ColumnNamesCsv(onlyWriteable bool) string

ColumnNamesCsv returns the CSV string of the column names

func (*ColumnHandler) ColumnValues

func (ch *ColumnHandler) ColumnValues(onlyWriteable bool) ([]interface{}, error)

func (*ColumnHandler) ColumnValuesCsv

func (ch *ColumnHandler) ColumnValuesCsv(onlyWriteable bool) (string, error)

func (*ColumnHandler) ColumnValuesPlaceholderCsv

func (ch *ColumnHandler) ColumnValuesPlaceholderCsv(onlyWriteable bool) (string, error)

func (*ColumnHandler) Unmarshal

func (ch *ColumnHandler) Unmarshal(row DataRow, entity DatabaseEntity) error

func (*ColumnHandler) Validate

func (ch *ColumnHandler) Validate() error

type Connection

type Connection interface {
	DB() *sql.DB
	Encryptor() *Encryptor
	Ping() error
	QueryRow(query string, args ...interface{}) (DataRow, error)
	Query(query string, args ...interface{}) (DataRows, error)
	Exec(query string, args ...interface{}) (sql.Result, error)
	Begin() (*TxConnection, error)
	Close() error
	Type() Type
	ID() string
	DBStats() *sql.DBStats
}

func NewTestConnection

func NewTestConnection(t *testing.T) Connection

type ConnectionFactory

type ConnectionFactory interface {
	Init(migrate bool) error
	NewConnection() (Connection, error)
	Reset() error
}

func NewConnectionFactory

func NewConnectionFactory(configFile string, migrate bool, debug bool) (ConnectionFactory, error)

func NewTestConnectionFactory

func NewTestConnectionFactory(t *testing.T) ConnectionFactory

type ContainerBootstrap

type ContainerBootstrap interface {
	testcontainers.Container
	Bootstrap(ctx context.Context) error

	ExecutionID() string
	// contains filtered or unexported methods
}

ContainerBootstrap is a testcontainer that can be bootstrapped and started from a given context

func BootstrapNewPostgresContainer

func BootstrapNewPostgresContainer(ctx context.Context, settings PostgresContainerSettings) (ContainerBootstrap, error)

type ContainerLogListener

type ContainerLogListener struct {
	*zap.SugaredLogger
}

func NewConsoleContainerLogListener

func NewConsoleContainerLogListener(debug bool) *ContainerLogListener

func (*ContainerLogListener) Accept

func (s *ContainerLogListener) Accept(l testcontainers.Log)

type ContainerRuntime

type ContainerRuntime interface {
	ContainerBootstrap
	ConnectionFactory
}

type ContainerSettings

type ContainerSettings interface {
	// contains filtered or unexported methods
}

type ContainerTestSuite

type ContainerTestSuite struct {
	*TransactionAwareDatabaseContainerTestSuite
}

func IsolatedContainerTestSuite

func IsolatedContainerTestSuite(
	t *testing.T, debug bool, settings ContainerSettings, commitAfterExecution bool,
) *ContainerTestSuite

func LeaseSharedContainerTestSuite

func LeaseSharedContainerTestSuite(t *testing.T, settings ContainerSettings, debug bool, commitAfterExecution bool) *ContainerTestSuite

func NewManagedContainerTestSuite

func NewManagedContainerTestSuite(
	debug bool,
	settings ContainerSettings,
	commitAfterExecution bool,
	listener testcontainers.LogConsumer,
) *ContainerTestSuite

func NewUnmanagedContainerTestSuite

func NewUnmanagedContainerTestSuite(
	ctx context.Context, containerRuntime ContainerRuntime, commitAfterExecution bool,
	listener testcontainers.LogConsumer,
) *ContainerTestSuite

type DataRow

type DataRow interface {
	Scan(dest ...interface{}) error
}

DataRow introduces a interface which is implemented by sql.Row and sql.Rows to make both usable for retrieving raw data

type DataRows

type DataRows interface {
	Scan(dest ...interface{}) error
	Next() bool
}

type DatabaseEntity

type DatabaseEntity interface {
	Table() string
	Marshaller() *EntityMarshaller
	New() DatabaseEntity
	Equal(other DatabaseEntity) bool
}

type Delete

type Delete struct {
	*Query
	// contains filtered or unexported fields
}

DELETE:

func (*Delete) Exec

func (d *Delete) Exec() (int64, error)

func (*Delete) NextPlaceholderCount

func (d *Delete) NextPlaceholderCount() int

func (*Delete) Where

func (d *Delete) Where(conditions map[string]interface{}) *Delete

func (*Delete) WhereIn

func (d *Delete) WhereIn(field, subQuery string, args ...interface{}) *Delete

func (*Delete) WhereRaw

func (d *Delete) WhereRaw(stmt string, args ...interface{}) *Delete

type EncryptionKeyFileConfig

type EncryptionKeyFileConfig string

EncryptionKeyFileConfig is currently just an encryption key file but could be extended at will for further configuration

type Encryptor

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

func NewEncryptor

func NewEncryptor(key string) (*Encryptor, error)

func (*Encryptor) Decrypt

func (e *Encryptor) Decrypt(encData string) (string, error)

func (*Encryptor) Decryptable

func (e *Encryptor) Decryptable(encData string) bool

Decryptable verifies whether the encrypted data can be decrypted by this Encryptor instance

func (*Encryptor) Encrypt

func (e *Encryptor) Encrypt(data string) (string, error)

func (*Encryptor) KeyID

func (e *Encryptor) KeyID() string

KeyID returns the first characters of the MD5 keys checksum as HEX string

type EntityMarshaller

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

func NewEntityMarshaller

func NewEntityMarshaller(entity interface{}) *EntityMarshaller

func (*EntityMarshaller) AddMarshaller

func (es *EntityMarshaller) AddMarshaller(field string, fct func(value interface{}) (interface{}, error))

func (*EntityMarshaller) AddUnmarshaller

func (es *EntityMarshaller) AddUnmarshaller(field string, fct func(value interface{}) (interface{}, error))

func (*EntityMarshaller) Marshal

func (es *EntityMarshaller) Marshal() (map[string]interface{}, error)

func (*EntityMarshaller) Unmarshal

func (es *EntityMarshaller) Unmarshal(rawData map[string]interface{}) error

type Insert

type Insert struct {
	*Query
	// contains filtered or unexported fields
}

INSERT:

func (*Insert) Exec

func (i *Insert) Exec() error

type InvalidEntityError

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

func (*InvalidEntityError) Error

func (e *InvalidEntityError) Error() string

type MigrationConfig

type MigrationConfig string

MigrationConfig is currently just a migrationConfig directory but could be extended at will for further configuration

var NoOpMigrationConfig MigrationConfig

NoOpMigrationConfig is a shortcut to not have any migrationConfig at all

type MockConnection

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

func (*MockConnection) Begin

func (c *MockConnection) Begin() (*TxConnection, error)

func (*MockConnection) Close

func (c *MockConnection) Close() error

func (*MockConnection) DB

func (c *MockConnection) DB() *sql.DB

func (*MockConnection) DBStats

func (c *MockConnection) DBStats() *sql.DBStats

func (*MockConnection) Encryptor

func (c *MockConnection) Encryptor() *Encryptor

func (*MockConnection) Exec

func (c *MockConnection) Exec(query string, args ...interface{}) (sql.Result, error)

func (*MockConnection) ID

func (c *MockConnection) ID() string

func (*MockConnection) Ping

func (c *MockConnection) Ping() error

func (*MockConnection) Query

func (c *MockConnection) Query(query string, args ...interface{}) (DataRows, error)

func (*MockConnection) QueryRow

func (c *MockConnection) QueryRow(query string, args ...interface{}) (DataRow, error)

func (*MockConnection) Type

func (c *MockConnection) Type() Type

type MockDataRow

type MockDataRow struct {
}

func (*MockDataRow) Scan

func (dr *MockDataRow) Scan(_ ...interface{}) error

type MockDataRows

type MockDataRows struct {
	*MockDataRow
}

func (*MockDataRows) Next

func (dr *MockDataRows) Next() bool

type MockDbEntity

type MockDbEntity struct {
	Col1 string `db:"notNull"`
	Col2 bool   `db:"readOnly"`
	Col3 int    `db:"encrypt"`
}

func (*MockDbEntity) Equal

func (fake *MockDbEntity) Equal(_ DatabaseEntity) bool

func (*MockDbEntity) Marshaller

func (fake *MockDbEntity) Marshaller() *EntityMarshaller

func (*MockDbEntity) New

func (fake *MockDbEntity) New() DatabaseEntity

func (*MockDbEntity) String

func (fake *MockDbEntity) String() string

func (*MockDbEntity) Table

func (fake *MockDbEntity) Table() string

type MockResult

type MockResult struct {
}

func (*MockResult) LastInsertId

func (r *MockResult) LastInsertId() (int64, error)

func (*MockResult) RowsAffected

func (r *MockResult) RowsAffected() (int64, error)

type PostgresContainer

type PostgresContainer struct {
	testcontainers.Container

	DebugLogs bool
	// contains filtered or unexported fields
}

PostgresContainer is a testcontainer that is able to provision a postgres Database with given credentials

func NewPostgresContainer

func NewPostgresContainer(settings PostgresContainerSettings) PostgresContainer

func (*PostgresContainer) Bootstrap

func (s *PostgresContainer) Bootstrap(ctx context.Context) error

func (*PostgresContainer) ExecutionID

func (s *PostgresContainer) ExecutionID() string

type PostgresContainerRuntime

type PostgresContainerRuntime struct {
	ContainerBootstrap
	ConnectionFactory
	// contains filtered or unexported fields
}

func RunPostgresContainer

func RunPostgresContainer(ctx context.Context, settings PostgresContainerSettings, debug bool) (*PostgresContainerRuntime, error)

type PostgresContainerSettings

type PostgresContainerSettings struct {
	Name              string
	Image             string
	Config            MigrationConfig
	Host              string
	Database          string
	Port              int
	User              string
	Password          string
	SslMode           string
	SslRootCert       string
	EncryptionKeyFile EncryptionKeyFileConfig
}

type Query

type Query struct {
	Conn Connection

	Logger *zap.SugaredLogger
	// contains filtered or unexported fields
}

func NewQuery

func NewQuery(conn Connection, entity DatabaseEntity, logger *zap.SugaredLogger) (*Query, error)

func (*Query) Delete

func (q *Query) Delete() *Delete

func (*Query) Insert

func (q *Query) Insert() *Insert

func (*Query) Select

func (q *Query) Select() *Select

func (*Query) SelectColumn

func (q *Query) SelectColumn(fieldName string) (*Select, error)

func (Query) String

func (q Query) String() string

func (*Query) Update

func (q *Query) Update() *Update

type Select

type Select struct {
	*Query
	// contains filtered or unexported fields
}

SELECT:

func (*Select) GetArgs

func (s *Select) GetArgs() []interface{}

GetArgs returns a copy of current Select arguments

func (*Select) GetMany

func (s *Select) GetMany() ([]DatabaseEntity, error)

func (*Select) GetOne

func (s *Select) GetOne() (DatabaseEntity, error)

func (*Select) GroupBy

func (s *Select) GroupBy(args []string) *Select

func (*Select) Limit

func (s *Select) Limit(limit int) *Select

func (*Select) NextPlaceholderCount

func (s *Select) NextPlaceholderCount() int

func (*Select) OrderBy

func (s *Select) OrderBy(args map[string]string) *Select

func (*Select) Where

func (s *Select) Where(conds map[string]interface{}) *Select

func (*Select) WhereIn

func (s *Select) WhereIn(field, subQuery string, args ...interface{}) *Select

func (*Select) WhereRaw

func (s *Select) WhereRaw(stmt string, args ...interface{}) *Select

type TransactionAwareDatabaseContainerTestSuite

type TransactionAwareDatabaseContainerTestSuite struct {
	context.Context
	suite.Suite

	ContainerRuntime
	testcontainers.LogConsumer
	// contains filtered or unexported fields
}

TransactionAwareDatabaseContainerTestSuite manages a test suiteSpec that handles a transaction-enabled connection. It can open a connection for you and will roll it back once the suiteSpec is finished. You can enable non-isolated runs (not preferred, edge cases only) by enabling CommitAfterExecution. It is possible to then also enable SchemaResetOnSetup to make sure that you are working from a clean Database. You are able to change the isolation level to per-method to ensure a rollback occurs after every method. The connections in this test suiteSpec are created lazily, so using it's provided TxConnection will only cause a connection to the Database if the test actually establishes the connection. In case this is important for benchmarks, retrieve the connection first to make it does not influence your results. This suite is based on a container runtime which will take care of the provisioned data container

func (*TransactionAwareDatabaseContainerTestSuite) SetupSuite

func (*TransactionAwareDatabaseContainerTestSuite) TearDownSuite

func (s *TransactionAwareDatabaseContainerTestSuite) TearDownSuite()

func (*TransactionAwareDatabaseContainerTestSuite) TxConnection

type TxConnection

type TxConnection struct {
	sync.Mutex
	// contains filtered or unexported fields
}

func NewTxConnection

func NewTxConnection(tx *sql.Tx, conn Connection, logger *zap.SugaredLogger) *TxConnection

func (*TxConnection) Begin

func (t *TxConnection) Begin() (*TxConnection, error)

func (*TxConnection) Close

func (t *TxConnection) Close() error

func (*TxConnection) DB

func (t *TxConnection) DB() *sql.DB

func (*TxConnection) DBStats

func (t *TxConnection) DBStats() *sql.DBStats

func (*TxConnection) Encryptor

func (t *TxConnection) Encryptor() *Encryptor

func (*TxConnection) Exec

func (t *TxConnection) Exec(query string, args ...interface{}) (sql.Result, error)

func (*TxConnection) GetTx

func (t *TxConnection) GetTx() *sql.Tx

func (*TxConnection) ID

func (t *TxConnection) ID() string

func (*TxConnection) Ping

func (t *TxConnection) Ping() error

func (*TxConnection) Query

func (t *TxConnection) Query(query string, args ...interface{}) (DataRows, error)

func (*TxConnection) QueryRow

func (t *TxConnection) QueryRow(query string, args ...interface{}) (DataRow, error)

func (*TxConnection) Rollback

func (t *TxConnection) Rollback() error

func (*TxConnection) Type

func (t *TxConnection) Type() Type

type Type

type Type string
const (
	Postgres Type = "postgres"
	SQLite   Type = "sqlite"
	Mock     Type = "mock"
)

type Update

type Update struct {
	*Query
	// contains filtered or unexported fields
}

UPDATE:

func (*Update) Exec

func (u *Update) Exec() error

func (*Update) ExecCount

func (u *Update) ExecCount() (int64, error)

func (*Update) Where

func (u *Update) Where(args map[string]interface{}) *Update

func (*Update) WhereNot

func (u *Update) WhereNot(args map[string]interface{}) *Update

type Validator

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

func NewValidator

func NewValidator(blockQueries bool, logger *zap.SugaredLogger) *Validator

func (*Validator) Validate

func (v *Validator) Validate(query string) error

Jump to

Keyboard shortcuts

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