You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
58 lines
1.2 KiB
58 lines
1.2 KiB
2 months ago
|
package mysql
|
||
|
|
||
|
import (
|
||
|
"strings"
|
||
|
|
||
|
"gorm.io/gorm"
|
||
|
"zestack.dev/cast"
|
||
|
)
|
||
|
|
||
|
// func init() {
|
||
|
// db.RegisterDriver("mysql", func(opts *db.DriverOptions) db.Driver {
|
||
|
// return &Driver{
|
||
|
// Migrator: Migrator{
|
||
|
// DB: opts.DB,
|
||
|
// Log: opts.Log,
|
||
|
// Retry: opts.Retry,
|
||
|
// },
|
||
|
// }
|
||
|
// })
|
||
|
// }
|
||
|
|
||
|
type Driver struct {
|
||
|
Migrator
|
||
|
}
|
||
|
|
||
|
func (*Driver) UseTenant(tx *gorm.DB, tenant uint) (reset func() error, err error) {
|
||
|
return UseDatabase(tx, TenantDatabase(tenant))
|
||
|
}
|
||
|
|
||
|
func (*Driver) CurrentTenant(tx *gorm.DB) (tenant uint, ok bool) {
|
||
|
databse := CurrentDatabase(tx)
|
||
|
basename := TenantBasename()
|
||
|
|
||
|
if databse != "" && strings.HasPrefix(databse, basename) {
|
||
|
var err error
|
||
|
tenant, err = cast.Uint(databse[len(basename):])
|
||
|
ok = err == nil && tenant > 0
|
||
|
}
|
||
|
|
||
|
return
|
||
|
}
|
||
|
|
||
|
func createSharedSchema(tx *gorm.DB) error {
|
||
|
database := PublicDatabase()
|
||
|
sql := "CREATE DATABASE IF NOT EXISTS " + tx.Statement.Quote(database)
|
||
|
return tx.Exec(sql).Error
|
||
|
}
|
||
|
|
||
|
func (d *Driver) CreateTenantSchema(tx *gorm.DB, tenantId uint) error {
|
||
|
database := TenantDatabase(tenantId)
|
||
|
sql := "CREATE DATABASE IF NOT EXISTS " + tx.Statement.Quote(database)
|
||
|
return tx.Exec(sql).Error
|
||
|
}
|
||
|
|
||
|
func (d *Driver) DropSchemaForTenant(tenant uint) error {
|
||
|
return d.DropDatabaseForTenant(tenant)
|
||
|
}
|