go.charczuk.com@v0.0.0-20240327042549-bc490516bd1a/sdk/db/table_name.go (about) 1 /* 2 3 Copyright (c) 2023 - Present. Will Charczuk. All rights reserved. 4 Use of this source code is governed by a MIT license that can be found in the LICENSE file at the root of the repository. 5 6 */ 7 8 package db 9 10 import "reflect" 11 12 // TableNameByType returns the table name for a given reflect.Type by instantiating it and calling o.TableName(). 13 // The type must implement DatabaseMapped or an exception will be returned. 14 func TableNameByType(t reflect.Type) string { 15 instance := reflect.New(t).Interface() 16 if typed, isTyped := instance.(TableNameProvider); isTyped { 17 return typed.TableName() 18 } 19 if t.Kind() == reflect.Ptr { 20 t = t.Elem() 21 instance = reflect.New(t).Interface() 22 if typed, isTyped := instance.(TableNameProvider); isTyped { 23 return typed.TableName() 24 } 25 } 26 return t.Name() 27 } 28 29 // TableName returns the mapped table name for a given instance; it will sniff for the `TableName()` function on the type. 30 func TableName(obj any) string { 31 if typed, isTyped := obj.(TableNameProvider); isTyped { 32 return typed.TableName() 33 } 34 return reflectType(obj).Name() 35 }