diff --git a/cmds/delete.go b/cmds/delete.go index 0fb239d..84c7bf8 100644 --- a/cmds/delete.go +++ b/cmds/delete.go @@ -1,7 +1,10 @@ package cmds import ( + "bytes" + "go/format" "os" + "text/template" "github.com/spf13/cobra" ) @@ -25,5 +28,34 @@ func deleteRun(cmd *cobra.Command, args []string) { } func generateDeletes() [][]byte { - return [][]byte{} + t, err := template.New("delete.tpl").Funcs(template.FuncMap{ + "makeGoColName": makeGoColName, + }).ParseFiles("templates/delete.tpl") + + if err != nil { + errorQuit(err) + } + + var outputs [][]byte + + for i := 0; i < len(cmdData.TablesInfo); i++ { + data := tplData{ + TableName: cmdData.TableNames[i], + TableData: cmdData.TablesInfo[i], + } + + var buf bytes.Buffer + if err = t.Execute(&buf, data); err != nil { + errorQuit(err) + } + + out, err := format.Source(buf.Bytes()) + if err != nil { + errorQuit(err) + } + + outputs = append(outputs, out) + } + + return outputs } diff --git a/templates/delete.tpl b/templates/delete.tpl new file mode 100644 index 0000000..bf19de7 --- /dev/null +++ b/templates/delete.tpl @@ -0,0 +1,13 @@ +{{- $tableName := .TableName -}} +func Delete{{makeGoColName $tableName}}(id int, db *sqlx.DB) error { + if id == nil { + return nil, errors.New("No ID provided for {{makeGoColName $tableName}} delete") + } + + err := db.Exec("DELETE FROM {{$tableName}} WHERE id=$1", id) + if err != nil { + return errors.New("Unable to delete from {{$tableName}}: %s", err) + } + + return nil +}