postgres

package
v5.10.1 Latest Latest
Warning

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

Go to latest
Published: Apr 26, 2024 License: Apache-2.0 Imports: 4 Imported by: 0

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func GetSchemaNameFromDb

func GetSchemaNameFromDb(tx *gorm.DB) (string, error)

GetSchemaNameFromDb retrieves the schema name from the given gorm.DB transaction. It first checks if the table expression is not nil, then extracts the schema name from the table expression SQL. If the schema name is empty, it returns an error.

It is intended to be used in a gorm hook, such as BeforeCreate, BeforeUpdate, etc.

Example:

type User struct {
	gorm.Model
	Username string
}

func (User) TableName() string {
	return "domain1.mock_private"
}

func (User) BeforeCreate(tx *gorm.DB) (err error) {
	schemaName, err := postgres.GetSchemaNameFromDb(tx) // schemaName = "domain1"
	if err != nil {
		return err
	}
	// ... do something with schemaName
	return nil
}

Types

type ResetSearchPath

type ResetSearchPath func() error

ResetSearchPath is a function that resets the search path to the default value.

func SetSearchPath

func SetSearchPath(db *gorm.DB, schemaName string) (*gorm.DB, ResetSearchPath)

SetSearchPath sets the search path for the given database connection to the specified schema name. It returns the modified database connection and a function that can be used to reset the search path to the default 'public' schema. If the schema name is invalid or starts with 'pg_', an error is added to the database connection's error list.

Example:

db, reset := postgres.SetSearchPath(db, "domain1")
if db.Error != nil {
	// handle the error
}
defer reset() // reset the search path to 'public'
// ... do something with the database connection (with the search path set to 'domain1')

Jump to

Keyboard shortcuts

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