@@ -4,20 +4,34 @@ import (
44 "bufio"
55 "bytes"
66 "context"
7- "io"
7+ _ "embed"
8+ "encoding/json"
89 "strings"
10+ "text/template"
911
10- easyjson "github.com/mailru/easyjson"
11- plugin "github.com/tabbed/sqlc-go/codegen"
12+ "buf.build/gen/go/sqlc/sqlc/protocolbuffers/go/protos/plugin"
1213
1314 "github.com/tabbed/sqlc-gen-kotlin/internal/core"
14- "github.com/tabbed/sqlc-gen-kotlin/internal/tmpl "
15+ "github.com/tabbed/sqlc-go/sdk "
1516)
1617
17- func Generate (ctx context.Context , req * plugin.Request ) (* plugin.Response , error ) {
18+ //go:embed tmpl/ktmodels.tmpl
19+ var ktModelsTmpl string
20+
21+ //go:embed tmpl/ktsql.tmpl
22+ var ktSqlTmpl string
23+
24+ //go:embed tmpl/ktiface.tmpl
25+ var ktIfaceTmpl string
26+
27+ func Offset (v int ) int {
28+ return v + 1
29+ }
30+
31+ func Generate (ctx context.Context , req * plugin.CodeGenRequest ) (* plugin.CodeGenResponse , error ) {
1832 var conf core.Config
1933 if len (req .PluginOptions ) > 0 {
20- if err := easyjson .Unmarshal (req .PluginOptions , & conf ); err != nil {
34+ if err := json .Unmarshal (req .PluginOptions , & conf ); err != nil {
2135 return nil , err
2236 }
2337 }
@@ -36,6 +50,17 @@ func Generate(ctx context.Context, req *plugin.Request) (*plugin.Response, error
3650 Queries : queries ,
3751 }
3852
53+ funcMap := template.FuncMap {
54+ "lowerTitle" : sdk .LowerTitle ,
55+ "comment" : sdk .DoubleSlashComment ,
56+ "imports" : i .Imports ,
57+ "offset" : Offset ,
58+ }
59+
60+ modelsFile := template .Must (template .New ("table" ).Funcs (funcMap ).Parse (ktModelsTmpl ))
61+ sqlFile := template .Must (template .New ("table" ).Funcs (funcMap ).Parse (ktSqlTmpl ))
62+ ifaceFile := template .Must (template .New ("table" ).Funcs (funcMap ).Parse (ktIfaceTmpl ))
63+
3964 core .DefaultImporter = i
4065
4166 tctx := core.KtTmplCtx {
@@ -50,11 +75,11 @@ func Generate(ctx context.Context, req *plugin.Request) (*plugin.Response, error
5075
5176 output := map [string ]string {}
5277
53- execute := func (name string , f func (io. Writer , core. KtTmplCtx ) error ) error {
78+ execute := func (name string , t * template. Template ) error {
5479 var b bytes.Buffer
5580 w := bufio .NewWriter (& b )
5681 tctx .SourceName = name
57- err := f (w , tctx )
82+ err := t . Execute (w , tctx )
5883 w .Flush ()
5984 if err != nil {
6085 return err
@@ -66,13 +91,13 @@ func Generate(ctx context.Context, req *plugin.Request) (*plugin.Response, error
6691 return nil
6792 }
6893
69- if err := execute ("Models.kt" , tmpl . KtModels ); err != nil {
94+ if err := execute ("Models.kt" , modelsFile ); err != nil {
7095 return nil , err
7196 }
72- if err := execute ("Queries.kt" , tmpl . KtIface ); err != nil {
97+ if err := execute ("Queries.kt" , ifaceFile ); err != nil {
7398 return nil , err
7499 }
75- if err := execute ("QueriesImpl.kt" , tmpl . KtSQL ); err != nil {
100+ if err := execute ("QueriesImpl.kt" , sqlFile ); err != nil {
76101 return nil , err
77102 }
78103
0 commit comments