|
| 1 | +package cmd |
| 2 | + |
| 3 | +import ( |
| 4 | + "strings" |
| 5 | + |
| 6 | + "github.com/sqlc-dev/sqlc/internal/config" |
| 7 | + "github.com/sqlc-dev/sqlc/internal/plugin" |
| 8 | +) |
| 9 | + |
| 10 | +const ( |
| 11 | + queryCommentFormatMarginalia = "marginalia" |
| 12 | + queryCommentFormatSQLCommenter = "sqlcommenter" |
| 13 | +) |
| 14 | + |
| 15 | +func applyQueryComments(req *plugin.GenerateRequest, opts config.QueryComments) { |
| 16 | + if !opts.Enabled { |
| 17 | + return |
| 18 | + } |
| 19 | + for _, query := range req.Queries { |
| 20 | + if query.Text == "" { |
| 21 | + continue |
| 22 | + } |
| 23 | + comment := queryComment(query, opts) |
| 24 | + if comment == "" { |
| 25 | + continue |
| 26 | + } |
| 27 | + query.Text = comment + " " + query.Text |
| 28 | + } |
| 29 | +} |
| 30 | + |
| 31 | +func queryComment(query *plugin.Query, opts config.QueryComments) string { |
| 32 | + tags := opts.Tags |
| 33 | + if len(tags) == 0 { |
| 34 | + tags = []string{"name"} |
| 35 | + } |
| 36 | + |
| 37 | + parts := make([]string, 0, len(tags)) |
| 38 | + for _, tag := range tags { |
| 39 | + value := queryCommentValue(query, tag) |
| 40 | + if value == "" { |
| 41 | + continue |
| 42 | + } |
| 43 | + key := "sqlc_" + tag |
| 44 | + if opts.Format == queryCommentFormatMarginalia { |
| 45 | + parts = append(parts, key+":"+escapeQueryCommentValue(value)) |
| 46 | + } else { |
| 47 | + parts = append(parts, key+"='"+escapeQueryCommentValue(value)+"'") |
| 48 | + } |
| 49 | + } |
| 50 | + if len(parts) == 0 { |
| 51 | + return "" |
| 52 | + } |
| 53 | + return "/*" + strings.Join(parts, ",") + "*/" |
| 54 | +} |
| 55 | + |
| 56 | +func queryCommentValue(query *plugin.Query, tag string) string { |
| 57 | + switch tag { |
| 58 | + case "name": |
| 59 | + return query.Name |
| 60 | + case "cmd": |
| 61 | + return query.Cmd |
| 62 | + case "filename": |
| 63 | + return query.Filename |
| 64 | + default: |
| 65 | + return "" |
| 66 | + } |
| 67 | +} |
| 68 | + |
| 69 | +func escapeQueryCommentValue(value string) string { |
| 70 | + value = strings.ReplaceAll(value, "*/", "* /") |
| 71 | + value = strings.ReplaceAll(value, "\n", " ") |
| 72 | + value = strings.ReplaceAll(value, "\r", " ") |
| 73 | + value = strings.ReplaceAll(value, "'", "%27") |
| 74 | + value = strings.ReplaceAll(value, ",", "%2C") |
| 75 | + value = strings.ReplaceAll(value, ":", "%3A") |
| 76 | + return value |
| 77 | +} |
0 commit comments