diff --git a/boilingcore/output.go b/boilingcore/output.go index d91f870a7..d546bdfa9 100644 --- a/boilingcore/output.go +++ b/boilingcore/output.go @@ -14,6 +14,7 @@ import ( "github.com/friendsofgo/errors" "github.com/volatiletech/sqlboiler/v4/importers" + "golang.org/x/tools/imports" ) // Copied from the go source @@ -269,9 +270,15 @@ func executeTemplate(buf *bytes.Buffer, t *template.Template, name string, data } func formatBuffer(buf *bytes.Buffer) ([]byte, error) { - output, err := format.Source(buf.Bytes()) + // format and process imports to remove unused ones + src, err := imports.Process("", buf.Bytes(), nil /* options */) if err == nil { - return output, nil + var output []byte + // format the output + output, err = format.Source(src) + if err == nil { + return output, nil + } } matches := rgxSyntaxError.FindStringSubmatch(err.Error()) diff --git a/boilingcore/output_test.go b/boilingcore/output_test.go index 354af46ad..dd57ef7f2 100644 --- a/boilingcore/output_test.go +++ b/boilingcore/output_test.go @@ -70,6 +70,44 @@ func TestFormatBuffer(t *testing.T) { } } +func TestFormatBufferWithUnusedImports(t *testing.T) { + t.Parallel() + + src := ` + package main + + import ( + "fmt" + "os" + "strings" + ) + + func main() { + fmt.Println("Hello, World!") + } + ` + + buf := &bytes.Buffer{} + fmt.Fprint(buf, src) + + got, err := formatBuffer(buf) + if err != nil { + t.Error(err) + } + + // expect strings import to be removed + var importsToBeRemoved = []string{"os", "strings"} + for _, imp := range importsToBeRemoved { + if strings.Contains(string(got), imp) { + t.Errorf("import %s should be removed", imp) + } + } + + if !strings.Contains(string(got), "fmt") { + t.Error("fmt import should be present") + } +} + func TestOutputFilenameParts(t *testing.T) { t.Parallel() diff --git a/testdata/psql_test_schema.sql b/testdata/psql_test_schema.sql index 232776dbb..29ef41d89 100644 --- a/testdata/psql_test_schema.sql +++ b/testdata/psql_test_schema.sql @@ -455,3 +455,8 @@ CREATE TABLE "User" ( PRIMARY KEY ("id") ); + +-- Create view that joins jets and pilots +-- https://github.com/volatiletech/sqlboiler/issues/1279 +CREATE OR REPLACE VIEW jets_pilots AS SELECT jets.id AS jet_id, jets.name as name, pilots.name AS pilot_name FROM jets AS jets LEFT JOIN pilots AS pilots ON pilots.id=jets.pilot_id; +