Documentation
¶
Overview ¶
Package scopes provides a set of predefined multitenancy scopes for GORM.
Index ¶
Examples ¶
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
func WithTenantSchema ¶
WithTenantSchema returns a GORM scope function that prefixes the table name with the specified tenant schema.
The function supports different strategies for determining the table name, which are attempted in the following order:
- Direct specification via gorm.DB.Table.
- Model type set via gorm.DB.Model implementing driver.TenantTabler.
- Destination type implementing driver.TenantTabler.
If the table name cannot be determined, an error is added to the DB instance.
Examples (assuming the following model):
type Book struct { ... }
var _ driver.TenantTabler = new(Book)
func (Book) TableName() string { return "books" }
func (Book) IsSharedModel() bool { ... }
Direct table specification:
db.Table("books").Scopes(WithTenantSchema("tenant1")).Find(...)
// SELECT * FROM "tenant1"."books"
Inferred from `Model` call:
db.Model(&Book{}).Scopes(WithTenantSchema("tenant1")).Find(...)
// SELECT * FROM "tenant1"."books"
Inferred from the destination type:
db.Scopes(WithTenantSchema("tenant1")).Find(&[]Book{})
// SELECT * FROM "tenant1"."books"
Example ¶
package main
import (
"fmt"
"github.com/bartventer/gorm-multitenancy/v8/pkg/scopes"
"gorm.io/gorm"
"gorm.io/gorm/utils/tests"
)
type Book struct {
ID uint
Title string
}
func (Book) TableName() string { return "books" }
func (Book) IsSharedModel() bool { return true }
func main() {
db, err := gorm.Open(tests.DummyDialector{})
if err != nil {
panic(err)
}
queryFn := func(tx *gorm.DB) *gorm.DB {
return tx.Scopes(scopes.WithTenantSchema("tenant1")).Find(&Book{})
}
sqlstr := db.ToSQL(queryFn)
fmt.Println(sqlstr)
}
Output: SELECT * FROM `tenant1`.`books`
Types ¶
This section is empty.
Click to show internal directories.
Click to hide internal directories.