Documentation ¶
Overview ¶
Package postgres provides utilities for managing PostgreSQL schemas in a multi-tenant application.
Index ¶
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
func GetSchemaNameFromDb ¶
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 }
func ValidateTenantName ¶ added in v5.11.0
ValidateTenantName checks the validity of a provided tenant name. A tenant name is considered valid if it:
- Matches the pattern `^[_a-zA-Z][_a-zA-Z0-9]{2,}$`. This means it must start with an underscore or a letter, followed by at least two characters that can be underscores, letters, or numbers.
- Does not start with "pg_". The prefix "pg_" is reserved for system schemas in PostgreSQL.
If the tenant name is invalid, the function returns an error with a detailed explanation.
Types ¶
type ResetSearchPath ¶
type ResetSearchPath func() error
ResetSearchPath is a function that resets the search path to the default value.
func SetSearchPath ¶
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')