Documentation ¶
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 }
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. It also sets the tenant in the context of the database connection (using the TenantKey from the tenantcontext package). Additionally, it returns a function that can be used to reset the search path to the default "public" schema and clear the tenant from the context. The function takes a *gorm.DB object and a schemaName string as input parameters. It returns a modified *gorm.DB object, a ResetSearchPath function, and an error (if any). The ResetSearchPath function can be called to clear the tenant from the context and reset the search path to "public". If the schemaName is invalid or starts with "pg_", an error will be returned.
Example:
db, resetSearchPath, err := postgres.SetSearchPath(db, "domain1") if err != nil { fmt.Println(err) // nil } defer resetSearchPath() // ... do something with the database connection
After calling SetSearchPath, the tenant (in this case, "domain1") will be set in the context of the db object. This can be useful for multi-tenant applications where each tenant has its own schema.