github.com/mendersoftware/go-lib-micro@v0.0.0-20240304135804-e8e39c59b148/store/utils.go (about) 1 // Copyright 2023 Northern.tech AS 2 // 3 // Licensed under the Apache License, Version 2.0 (the "License"); 4 // you may not use this file except in compliance with the License. 5 // You may obtain a copy of the License at 6 // 7 // http://www.apache.org/licenses/LICENSE-2.0 8 // 9 // Unless required by applicable law or agreed to in writing, software 10 // distributed under the License is distributed on an "AS IS" BASIS, 11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 // See the License for the specific language governing permissions and 13 // limitations under the License. 14 package store 15 16 import ( 17 "context" 18 "strings" 19 20 "github.com/mendersoftware/go-lib-micro/identity" 21 ) 22 23 // DbFromContext generates database name using tenant field from identity extracted 24 // from context and original database name 25 func DbFromContext(ctx context.Context, origDbName string) string { 26 identity := identity.FromContext(ctx) 27 tenant := "" 28 if identity != nil { 29 tenant = identity.Tenant 30 } 31 32 return DbNameForTenant(tenant, origDbName) 33 } 34 35 type TenantDbMatchFunc func(name string) bool 36 37 // IsTenantDb returns a function of `TenantDbMatchFunc` that can be used for 38 // checking if database has a tenant DB name format 39 func IsTenantDb(baseDb string) TenantDbMatchFunc { 40 prefix := baseDb + "-" 41 return func(name string) bool { 42 return strings.HasPrefix(name, prefix) 43 } 44 } 45 46 // TenantFromDbName attempts to extract tenant ID from provided tenant DB name. 47 // Returns extracted tenant ID or an empty string. 48 func TenantFromDbName(dbName string, baseDb string) string { 49 noBase := strings.TrimPrefix(dbName, baseDb+"-") 50 if noBase == dbName { 51 return "" 52 } 53 return noBase 54 } 55 56 // DbNameForTenant composes tenant's db name. 57 func DbNameForTenant(tenantId string, baseDb string) string { 58 if tenantId == "" { 59 return baseDb 60 } 61 return baseDb + "-" + tenantId 62 }