scopes

package
v8.9.0 Latest Latest
Warning

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

Go to latest
Published: Jul 11, 2025 License: Apache-2.0 Imports: 3 Imported by: 0

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

func WithTenantSchema(tenant string) func(db *gorm.DB) *gorm.DB

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:

  1. Direct specification via gorm.DB.Table.
  2. Model type set via gorm.DB.Model implementing driver.TenantTabler.
  3. 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.

Jump to

Keyboard shortcuts

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