databases

package
v1.127.1 Latest Latest
Warning

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

Go to latest
Published: Oct 9, 2026 License: MIT Imports: 30 Imported by: 5

Documentation

Index

Constants

This section is empty.

Variables

View Source
var DXOrderByDirectionEnumSetAll = []any{DXOrderByDirectionAsc, DXOrderByDirectionDesc}
View Source
var DXOrderByNullPlacementEnumSetAll = []any{DXOrderByNullPlacementFirst, DXOrderByNullPlacementLast}

Functions

func CheckDatabaseError

func CheckDatabaseError(err error) error

CheckDatabaseError identifies common databases errors and returns standardized errors while preserving the original error information

func GetDriverSpecificErrorMessage

func GetDriverSpecificErrorMessage(err error) string

GetDriverSpecificErrorMessage extracts the specific error message from different databases drivers

func IsConnectionError

func IsConnectionError(err error) bool

IsConnectionError detects databases connection issues across different databases systems

func IsConstraintViolationError added in v1.126.5

func IsConstraintViolationError(err error) bool

IsConstraintViolationError detects a row the database refused for a reason other than a duplicate key: a foreign-key, check or not-null violation. Such an error says the request carried a value the schema cannot take, which is the caller's problem, where a duplicate key is a conflict and anything else (a lost connection, a syntax error) is the server's. Checked by driver type first, then by message, in the same way as IsDuplicateKeyError.

func IsDuplicateKeyError

func IsDuplicateKeyError(err error) bool

IsDuplicateKeyError detects duplicate key violations across different databases systems

func IsErrorType

func IsErrorType(err, target error) bool

IsErrorType checks if an error is of a specific error type

func ReplaceErrorMessage

func ReplaceErrorMessage(originalErr error, newMessage string) error

ReplaceErrorMessage replaces the message of an error while preserving its stack trace

func ReplaceErrorWithDriverDetails

func ReplaceErrorWithDriverDetails(originalErr error, standardMessage string) error

ReplaceErrorWithDriverDetails replaces the error message with one that includes driver-specific details

Types

type DXDatabase

type DXDatabase struct {
	NameId                       string
	IsConfigured                 bool
	DatabaseType                 base.DXDatabaseType
	Address                      string
	UserName                     string
	UserPassword                 string
	DatabaseName                 string
	ConnectionOptions            string
	IsConnectAtStart             bool
	MustConnected                bool
	Connected                    bool
	Connection                   *sqlx.DB
	PgxPool                      *pgxpool.Pool
	ConnectionString             string
	NonSensitiveConnectionString string
	OnCannotConnect              DXDatabaseEventFunc
	CreateScriptFiles            []string
	ConcurrencySemaphore         chan struct{} // Adjust number based on your DB max_connections

	// Pool configuration
	PoolMaxOpenConns           int // Maximum open connections (0 = unlimited)
	PoolMaxIdleConns           int // Maximum idle connections
	PoolConnMaxLifetimeMinutes int // Maximum connection lifetime in minutes
	PoolConnMaxIdleTimeMinutes int // Maximum idle time in minutes before close
}

func (*DXDatabase) ApplyFromConfiguration

func (d *DXDatabase) ApplyFromConfiguration() (err error)

func (*DXDatabase) CheckConnection

func (d *DXDatabase) CheckConnection() (err error)

func (*DXDatabase) CheckConnectionAndReconnect

func (d *DXDatabase) CheckConnectionAndReconnect() (err error)

func (*DXDatabase) CheckIsErrorBecauseDbNotExist

func (d *DXDatabase) CheckIsErrorBecauseDbNotExist(err error) bool

func (*DXDatabase) Connect

func (d *DXDatabase) Connect() (err error)

func (*DXDatabase) Count

func (d *DXDatabase) Count(ctx context.Context, tableName string, whereAndFieldNameValues utils.JSON, joinSQLPart any) (count int64, err error)

func (*DXDatabase) Delete

func (d *DXDatabase) Delete(ctx context.Context, tableName string, whereAndFieldNameValues utils.JSON, returningFieldNames []string) (result sql.Result, returningFieldValues []utils.JSON, err error)

func (*DXDatabase) Disconnect

func (d *DXDatabase) Disconnect() (err error)

func (*DXDatabase) EnsureConnection

func (d *DXDatabase) EnsureConnection() (err error)

func (*DXDatabase) ExecuteCreateScripts

func (d *DXDatabase) ExecuteCreateScripts() (rs []sql.Result, err error)

func (*DXDatabase) ExecuteCreateScriptsFromEmbedded

func (d *DXDatabase) ExecuteCreateScriptsFromEmbedded(contentProvider SQLContentProvider) (rs []sql.Result, err error)

ExecuteCreateScriptsFromEmbedded executes create scripts using embedded content provider The contentProvider function should return SQL content for each path key in CreateScriptFiles

func (*DXDatabase) ExecuteFile

func (d *DXDatabase) ExecuteFile(filename string) (r sql.Result, err error)

func (*DXDatabase) ExecuteSQLContent

func (d *DXDatabase) ExecuteSQLContent(content string) (r sql.Result, err error)

ExecuteSQLContent executes SQL from string content (for embedded SQL)

func (*DXDatabase) ExecuteScript

func (d *DXDatabase) ExecuteScript(s *DXDatabaseScript) (err error)

func (*DXDatabase) GetConnectionString

func (d *DXDatabase) GetConnectionString() (s string, err error)

func (*DXDatabase) GetNonSensitiveConnectionString

func (d *DXDatabase) GetNonSensitiveConnectionString() string

func (*DXDatabase) Insert

func (d *DXDatabase) Insert(ctx context.Context, tableName string, setFieldValues utils.JSON, returningFieldNames []string) (result sql.Result, returningFieldValues utils.JSON, err error)

func (*DXDatabase) Select

func (d *DXDatabase) Select(ctx context.Context, tableName string, fieldTypeMapping db.DXDatabaseTableFieldTypeMapping, showFieldNames []string, whereAndFieldNameValues utils.JSON, joinSQLPart any,
	groupBy []string, havingClause utils.JSON, orderByFieldNameDirections db.DXDatabaseTableFieldsOrderBy,
	limit any, offset any, forUpdatePart any) (rowsInfo *db.DXDatabaseTableRowsInfo, resultDataRows []utils.JSON, err error)

func (*DXDatabase) SelectOne

func (d *DXDatabase) SelectOne(ctx context.Context, tableName string, fieldTypeMapping db.DXDatabaseTableFieldTypeMapping, fieldNames []string, whereAndFieldNameValues utils.JSON, joinSQLPart any,
	groupBy []string, havingClause utils.JSON, orderByFieldNameDirections db.DXDatabaseTableFieldsOrderBy, offset any, forUpdatePart any) (rowsInfo *db.DXDatabaseTableRowsInfo, resultDataRow utils.JSON, err error)

func (*DXDatabase) SelectPaging

func (d *DXDatabase) SelectPaging(ctx context.Context, pageIndex int64, rowsPerPage int64, tableName string, fieldTypeMapping db.DXDatabaseTableFieldTypeMapping, fieldNames []string, whereAndFieldNameValues utils.JSON, joinSQLPart any,
	groupBy []string, havingClause utils.JSON, orderByFieldNameDirections db.DXDatabaseTableFieldsOrderBy) (totalRowCount int64, rowsInfo *db.DXDatabaseTableRowsInfo, resultDataRows []utils.JSON, err error)

func (*DXDatabase) ShouldSelectOne

func (d *DXDatabase) ShouldSelectOne(ctx context.Context, tableName string, fieldTypeMapping db.DXDatabaseTableFieldTypeMapping, fieldNames []string, whereAndFieldNameValues utils.JSON, joinSQLPart any,
	groupBy []string, havingClause utils.JSON, orderByFieldNameDirections db.DXDatabaseTableFieldsOrderBy, offset any, forUpdatePart any) (
	rowsInfo *db.DXDatabaseTableRowsInfo, resultDataRow utils.JSON, err error)

func (*DXDatabase) SoftDelete

func (d *DXDatabase) SoftDelete(ctx context.Context, tableName string, whereAndFieldNameValues utils.JSON, returningFieldNames []string) (result sql.Result, returningFieldValues []utils.JSON, err error)

func (*DXDatabase) TransactionBegin

func (d *DXDatabase) TransactionBegin(ctx context.Context, isolationLevel DXDatabaseTxIsolationLevel) (dtx *DXDatabaseTx, err error)

func (*DXDatabase) Tx

func (d *DXDatabase) Tx(ctx context.Context, log *log.DXLog, isolationLevel sql.IsolationLevel, callback DXDatabaseTxCallback) (err error)

func (*DXDatabase) Update

func (d *DXDatabase) Update(ctx context.Context, tableName string, setFieldValues utils.JSON, whereAndFieldNameValues utils.JSON, returningFieldNames []string) (result sql.Result, returningFieldValues []utils.JSON, err error)

type DXDatabaseEventFunc

type DXDatabaseEventFunc func(dm *DXDatabase, err error)

type DXDatabaseManager

type DXDatabaseManager struct {
	Databases map[string]*DXDatabase
	Scripts   map[string]*DXDatabaseScript
	// contains filtered or unexported fields
}
var Manager DXDatabaseManager

func (*DXDatabaseManager) ConnectAll

func (dm *DXDatabaseManager) ConnectAll(configurationNameId string) (err error)

func (*DXDatabaseManager) ConnectAllAtStart

func (dm *DXDatabaseManager) ConnectAllAtStart() (err error)

func (*DXDatabaseManager) DisconnectAll

func (dm *DXDatabaseManager) DisconnectAll() (err error)

func (*DXDatabaseManager) Get

func (dm *DXDatabaseManager) Get(nameId string) *DXDatabase

Get returns an already-registered database, or nil. Unlike GetOrCreate it registers nothing, which is what a caller wants when a missing entry means "not configured yet" rather than "make me one".

func (*DXDatabaseManager) GetOrCreate

func (dm *DXDatabaseManager) GetOrCreate(nameId string) *DXDatabase

GetOrCreate gets an existing databases or creates a new one with default settings

func (*DXDatabaseManager) LoadFromConfiguration

func (dm *DXDatabaseManager) LoadFromConfiguration(configurationNameId string) (err error)

func (*DXDatabaseManager) Names

func (dm *DXDatabaseManager) Names() []string

Names returns the registered names, sorted.

func (*DXDatabaseManager) NewDatabase

func (dm *DXDatabaseManager) NewDatabase(nameId string, isConnectAtStart, mustBeConnected bool) *DXDatabase

func (*DXDatabaseManager) NewDatabaseScript

func (dm *DXDatabaseManager) NewDatabaseScript(nameId string, files []string) *DXDatabaseScript

func (*DXDatabaseManager) Set

func (dm *DXDatabaseManager) Set(nameId string, d *DXDatabase)

Set registers d under nameId, replacing any handle already there. It is the locked way to add a database the caller built and configured itself.

func (*DXDatabaseManager) Snapshot

func (dm *DXDatabaseManager) Snapshot() map[string]*DXDatabase

Snapshot returns a copy of the registry, safe to range while other goroutines register databases. Ranging dm.Databases directly is not: a concurrent map read and write is a fatal error.

type DXDatabaseScript

type DXDatabaseScript struct {
	Owner              *DXDatabaseManager
	NameId             string
	ManagementDatabase *DXDatabase
	Files              []string
}

func (*DXDatabaseScript) Execute

func (ds *DXDatabaseScript) Execute(d *DXDatabase) (rs []sql.Result, err error)

func (*DXDatabaseScript) ExecuteFile

func (ds *DXDatabaseScript) ExecuteFile(d *DXDatabase, filename string) (r sql.Result, err error)

type DXDatabaseTx

type DXDatabaseTx struct {
	*sqlx.Tx
	Database *DXDatabase
	Log      *log.DXLog
	Ctx      context.Context
}

func (*DXDatabaseTx) Count

func (dtx *DXDatabaseTx) Count(ctx context.Context, tableName string, whereAndFieldNameValues utils.JSON, joinSQLPart any, groupBy []string, havingClause utils.JSON) (count int64, err error)

func (*DXDatabaseTx) Finish

func (dtx *DXDatabaseTx) Finish(l *log.DXLog, err error)

Finish commits if no error, rollbacks if error

func (*DXDatabaseTx) Insert

func (dtx *DXDatabaseTx) Insert(ctx context.Context, tableName string, setFieldValues utils.JSON, returningFieldNames []string) (result sql.Result, returningFieldValues utils.JSON, err error)

func (*DXDatabaseTx) InsertWithEncryption

func (dtx *DXDatabaseTx) InsertWithEncryption(
	tableName string,
	data utils.JSON,
	encryptionColumnDefs []EncryptionColumnDef,
	returningFieldNames []string,
) (sql.Result, utils.JSON, error)

InsertWithEncryption inserts with encrypted columns Automatically sets session keys and builds encryption expressions

func (*DXDatabaseTx) Select

func (dtx *DXDatabaseTx) Select(ctx context.Context, tableName string, fieldTypeMapping db.DXDatabaseTableFieldTypeMapping, showFieldNames []string, whereAndFieldNameValues utils.JSON, joinSQLPart any, groupBy []string, havingClause utils.JSON, orderByFieldNameDirections db.DXDatabaseTableFieldsOrderBy,
	limit any, offset any, forUpdatePart any) (rowsInfo *db.DXDatabaseTableRowsInfo, resultData []utils.JSON, err error)

func (*DXDatabaseTx) SelectOne

func (dtx *DXDatabaseTx) SelectOne(ctx context.Context, tableName string, fieldTypeMapping db.DXDatabaseTableFieldTypeMapping, fieldNames []string, whereAndFieldNameValues utils.JSON, joinSQLPart any,
	groupBy []string, havingClause utils.JSON, orderByFieldNameDirections db.DXDatabaseTableFieldsOrderBy, offset any, forUpdatePart any) (rowsInfo *db.DXDatabaseTableRowsInfo, r utils.JSON, err error)

func (*DXDatabaseTx) SelectOneWithEncryption

func (dtx *DXDatabaseTx) SelectOneWithEncryption(
	tableName string,
	columns []string,
	encryptionColumnDefs []EncryptionColumnDef,
	where utils.JSON,
) (utils.JSON, error)

SelectOneWithEncryption selects one row with decrypted columns

func (*DXDatabaseTx) SelectWithEncryption

func (dtx *DXDatabaseTx) SelectWithEncryption(
	tableName string,
	columns []string,
	encryptionColumnDefs []EncryptionColumnDef,
	where utils.JSON,
	orderBy *string,
	limit *int,
) ([]utils.JSON, error)

SelectWithEncryption selects with decrypted columns

func (*DXDatabaseTx) ShouldSelectOne

func (dtx *DXDatabaseTx) ShouldSelectOne(ctx context.Context, tableName string, fieldTypeMapping db.DXDatabaseTableFieldTypeMapping, fieldNames []string, whereAndFieldNameValues utils.JSON, joinSQLPart any,
	groupBy []string, havingClause utils.JSON, orderByFieldNameDirections db.DXDatabaseTableFieldsOrderBy, offset any, forUpdatePart any) (
	rowsInfo *db.DXDatabaseTableRowsInfo, resultData utils.JSON, err error)

func (*DXDatabaseTx) TxDelete

func (dtx *DXDatabaseTx) TxDelete(ctx context.Context, tableName string, whereAndFieldNameValues utils.JSON, returningFieldNames []string) (result sql.Result, returningFieldValues []utils.JSON, err error)

func (*DXDatabaseTx) TxSetSessionKey

func (dtx *DXDatabaseTx) TxSetSessionKey(dbType base.DXDatabaseType, sourceType models.ModelDBKeySource, sourceValue string, sessionKey string) error

TxSetSessionKey sets a session-level configuration key in the transaction

Parameters:

  • dbType: databases type (PostgreSQL, SQLServer, Oracle, MariaDB)
  • sourceType: where to get the value from
  • sourceValue: meaning depends on sourceType:
  • ModelDBKeySourceRaw: the actual value to set
  • ModelDBKeySourceEnv: environment variable name
  • ModelDBKeySourceConfig: config key name (format: "configName.keyPath")
  • ModelDBKeySourceSecureMemory: secure memory key
  • sessionKey: the databases session config key name (e.g., "app.encryption_key")

func (*DXDatabaseTx) TxSetSessionKeyFromSecureMemory

func (dtx *DXDatabaseTx) TxSetSessionKeyFromSecureMemory(secureMemoryKey string, sessionKey string) error

TxSetSessionKeyFromSecureMemory is a convenience method to set session key from secure memory This simplifies the common case of loading encryption keys from secure memory into DB session DatabaseType is obtained from dtx.Database.DatabaseType

Parameters:

  • secureMemoryKey: the key name in secure memory (previously stored via secure_memory.Manager.StoreEnclave)
  • sessionKey: the databases session config key name (e.g., "app.encryption_key")

func (*DXDatabaseTx) TxSoftDelete

func (dtx *DXDatabaseTx) TxSoftDelete(ctx context.Context, tableName string, whereAndFieldNameValues utils.JSON, returningFieldNames []string) (result sql.Result, returningFieldValues []utils.JSON, err error)

func (*DXDatabaseTx) Update

func (dtx *DXDatabaseTx) Update(ctx context.Context, tableName string, setFieldValues utils.JSON, whereAndFieldNameValues utils.JSON, returningFieldNames []string) (result sql.Result, returningFieldValues []utils.JSON, err error)

func (*DXDatabaseTx) UpdateWithEncryption

func (dtx *DXDatabaseTx) UpdateWithEncryption(
	tableName string,
	data utils.JSON,
	encryptionColumnDefs []EncryptionColumnDef,
	where utils.JSON,
	returningFieldNames []string,
) (sql.Result, []utils.JSON, error)

UpdateWithEncryption updates with encrypted columns

type DXDatabaseTxCallback

type DXDatabaseTxCallback func(dtx *DXDatabaseTx) (err error)

type DXDatabaseTxIsolationLevel

type DXDatabaseTxIsolationLevel = sql.IsolationLevel
const (
	LevelDefault DXDatabaseTxIsolationLevel = iota
	LevelReadUncommitted
	LevelReadCommitted
	LevelWriteCommitted
	LevelRepeatableRead
	LevelSnapshot
	LevelSerializable
	LevelLinearizable
)

type DXOrderByDirection

type DXOrderByDirection string
const (
	DXOrderByDirectionAsc  DXOrderByDirection = "ASC"
	DXOrderByDirectionDesc DXOrderByDirection = "DESC"
)

type DXOrderByNullPlacement

type DXOrderByNullPlacement string
const (
	DXOrderByNullPlacementFirst DXOrderByNullPlacement = "FIRST"
	DXOrderByNullPlacementLast  DXOrderByNullPlacement = "LAST"
)

type EncryptionColumnDef

type EncryptionColumnDef struct {
	FieldName          string            // DB column name (e.g., "fullname_encrypted")
	DataFieldName      string            // field name in data JSON for INSERT/UPDATE (e.g., "fullname")
	AliasName          string            // output alias for SELECT decryption (e.g., "fullname")
	EncryptionKeyDef   *EncryptionKeyDef // encryption key definition (must not be nil when used)
	HashFieldName      string            // optional: hash field for searchable hash
	HashSaltMemoryKey  string            // optional: secure memory key for hash salt
	HashSaltSessionKey string            // optional: DB session key for hash salt
	ViewHasDecrypt     bool              // true = view already has pgp_sym_decrypt, just set session key
}

EncryptionColumnDef defines encryption config for a single column. Used for INSERT/UPDATE (encryption) and SELECT (decryption). Each usage context reads only the fields it needs; unused fields are ignored.

type EncryptionKeyDef

type EncryptionKeyDef struct {
	SecureMemoryKey string // key name in secure memory
	SessionKey      string // DB session key name
}

EncryptionKeyDef defines a session key needed for encryption/decryption operations. Use this when you only need the session key set (e.g., views that already handle decryption).

type SQLContentProvider

type SQLContentProvider func(path string) (string, error)

SQLContentProvider is a function type that returns SQL content for a given path key

type StackTraceError

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

StackTraceError is a custom error type that preserves stack traces

func (*StackTraceError) Cause

func (e *StackTraceError) Cause() error

Cause returns the underlying cause of the error

func (*StackTraceError) Error

func (e *StackTraceError) Error() string

Error returns the error message

func (*StackTraceError) Format

func (e *StackTraceError) Format(s fmt.State, verb rune)

Format implements fmt.Formatter to properly format the error This makes it work with fmt.Printf("%+v", err)

func (*StackTraceError) StackTrace

func (e *StackTraceError) StackTrace() errors.StackTrace

StackTrace returns the preserved stack trace

func (*StackTraceError) Unwrap

func (e *StackTraceError) Unwrap() error

Unwrap supports Go 1.13+ error unwrapping

Directories

Path Synopsis
db

Jump to

Keyboard shortcuts

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