github.com/Ali-iotechsys/sqlboiler/v4@v4.0.0-20221208124957-6aec9a5f1f71/drivers/registration.go (about) 1 package drivers 2 3 import ( 4 "fmt" 5 "os" 6 "os/exec" 7 "path/filepath" 8 "strings" 9 ) 10 11 // registeredDrivers are all the drivers which are currently registered 12 var registeredDrivers = map[string]Interface{} 13 14 // RegisterBinary is used to register drivers that are binaries. 15 // Panics if a driver with the same name has been previously loaded. 16 func RegisterBinary(name, path string) { 17 register(name, binaryDriver(path)) 18 } 19 20 // RegisterFromInit is typically called by a side-effect loaded driver 21 // during init time. 22 // Panics if a driver with the same name has been previously loaded. 23 func RegisterFromInit(name string, driver Interface) { 24 register(name, driver) 25 } 26 27 // GetDriver retrieves the driver by name 28 func GetDriver(name string) Interface { 29 if d, ok := registeredDrivers[name]; ok { 30 return d 31 } 32 33 panic(fmt.Sprintf("drivers: sqlboiler driver %s has not been registered", name)) 34 } 35 36 func register(name string, driver Interface) { 37 if _, ok := registeredDrivers[name]; ok { 38 panic(fmt.Sprintf("drivers: sqlboiler driver %s already loaded", name)) 39 } 40 41 registeredDrivers[name] = driver 42 } 43 44 // RegisterBinaryFromCmdArg is used to register drivers from a command line argument 45 // The argument is either just the driver name or a path to a specific driver 46 // Panics if a driver with the same name has been previously loaded. 47 func RegisterBinaryFromCmdArg(arg string) (name, path string, err error) { 48 path, err = getFullPath(arg) 49 if err != nil { 50 return name, path, err 51 } 52 53 name = getNameFromPath(path) 54 55 RegisterBinary(name, path) 56 57 return name, path, nil 58 } 59 60 // Get the full path to the driver binary from the given path 61 // the path can also be just the driver name e.g. "psql" 62 func getFullPath(path string) (string, error) { 63 var err error 64 65 if strings.ContainsRune(path, os.PathSeparator) { 66 return path, nil 67 } 68 69 path, err = exec.LookPath("sqlboiler-" + path) 70 if err != nil { 71 return path, fmt.Errorf("could not find driver executable: %w", err) 72 } 73 74 path, err = filepath.Abs(path) 75 if err != nil { 76 return path, fmt.Errorf("could not find absolute path to driver: %w", err) 77 } 78 79 return path, nil 80 } 81 82 // Get the driver name from the path. 83 // strips the "sqlboiler-" prefix if it exists 84 // strips the ".exe" suffix if it exits 85 func getNameFromPath(name string) string { 86 name = strings.Replace(filepath.Base(name), "sqlboiler-", "", 1) 87 name = strings.Replace(name, ".exe", "", 1) 88 89 return name 90 }