github.com/Ali-iotechsys/sqlboiler/v4@v4.0.0-20221208124957-6aec9a5f1f71/drivers/binary_driver.go (about) 1 package drivers 2 3 import ( 4 "bytes" 5 "encoding/json" 6 "io" 7 "os" 8 "os/exec" 9 10 "github.com/friendsofgo/errors" 11 "github.com/volatiletech/sqlboiler/v4/importers" 12 ) 13 14 type binaryDriver string 15 16 // Assemble calls out to the binary with JSON 17 // The contract for error messages is that a plain text error message is delivered 18 // and the exit status of the process is non-zero 19 func (b binaryDriver) Assemble(config Config) (*DBInfo, error) { 20 var dbInfo DBInfo 21 err := execute(string(b), "assemble", config, &dbInfo, os.Stderr) 22 if err != nil { 23 return nil, err 24 } 25 26 return &dbInfo, nil 27 } 28 29 // Templates calls the templates function to get a map of overidden file names 30 // and their contents in base64 31 func (b binaryDriver) Templates() (map[string]string, error) { 32 var templates map[string]string 33 err := execute(string(b), "templates", nil, &templates, os.Stderr) 34 if err != nil { 35 return nil, err 36 } 37 38 return templates, nil 39 } 40 41 // Imports calls the imports function to get imports from the driver 42 func (b binaryDriver) Imports() (col importers.Collection, err error) { 43 err = execute(string(b), "imports", nil, &col, os.Stderr) 44 if err != nil { 45 return col, err 46 } 47 48 return col, nil 49 } 50 51 func execute(executable, method string, input interface{}, output interface{}, errStream io.Writer) error { 52 var err error 53 var inputBytes []byte 54 if input != nil { 55 inputBytes, err = json.Marshal(input) 56 if err != nil { 57 return errors.Wrap(err, "failed to json-ify driver configuration") 58 } 59 } 60 61 outputBytes := &bytes.Buffer{} 62 cmd := exec.Command(executable, method) 63 cmd.Stdout = outputBytes 64 cmd.Stderr = errStream 65 if inputBytes != nil { 66 cmd.Stdin = bytes.NewReader(inputBytes) 67 } 68 err = cmd.Run() 69 70 if err != nil { 71 if ee, ok := err.(*exec.ExitError); ok { 72 if ee.ProcessState.Exited() && !ee.ProcessState.Success() { 73 return errors.Wrapf(err, "driver (%s) exited non-zero", executable) 74 } 75 } 76 77 return errors.Wrapf(err, "something totally unexpected happened when running the binary driver %s", executable) 78 } 79 80 if err = json.Unmarshal(outputBytes.Bytes(), &output); err != nil { 81 return errors.Wrap(err, "failed to marshal json from binary") 82 } 83 84 return nil 85 }