Skip to content

Instantly share code, notes, and snippets.

@Karitham
Created July 2, 2021 10:04
Show Gist options
  • Save Karitham/565030ae72daa81ca8c43ebba83f6d8a to your computer and use it in GitHub Desktop.
Save Karitham/565030ae72daa81ca8c43ebba83f6d8a to your computer and use it in GitHub Desktop.
SQL to Go struct

SQL to Go struct

Simple program to transform SQL queries to go structs.

The fields need to have a as clause for now.

Example

SELECT inbounds.count as inbounds_count,
    inbounds.last_week as inbounds_last_week,
    inbounds.most_active_user as inbounds_most_active_user,
    outbounds.count as outbounds_count,
    outbounds.last_week as outbounds_last_week,
    outbounds.most_active_user as outbounds_most_active_user,
    locations.count as locations_count,
    users.count as user_count,
    items.count as items_count,
    items.avg_price as items_avg_price,
    items.total_price as items_total_price
FROM .....

Outputs

type AutoGenerated struct {
	InboundsCount string `json:"inbounds_count"`
	InboundsLastWeek string `json:"inbounds_last_week"`
	InboundsMostActiveUser string `json:"inbounds_most_active_user"`
	OutboundsCount string `json:"outbounds_count"`
	OutboundsLastWeek string `json:"outbounds_last_week"`
	OutboundsMostActiveUser string `json:"outbounds_most_active_user"`
	LocationsCount string `json:"locations_count"`
	UserCount string `json:"user_count"`
	ItemsCount string `json:"items_count"`
	ItemsAvgPrice string `json:"items_avg_price"`
	ItemsTotalPrice string `json:"items_total_price"`
}
package main
import (
"bufio"
"bytes"
"os"
"regexp"
"strings"
)
var FieldRegex = regexp.MustCompile(`[SELECTselect\s]*\w+\.\w+\s*as\s*(\w+)[,\s]*`)
func main() {
r := bufio.NewReader(os.Stdin)
buf := &bytes.Buffer{}
for {
s, err := r.ReadString('\n')
buf.WriteString(s)
if err != nil {
break
}
}
fields := FieldRegex.FindAllStringSubmatch(buf.String(), -1)
finalFields := make([]string, 0)
for _, f := range fields {
finalFields = append(finalFields, f[1])
}
strc := BuildStructFromFields(finalFields)
os.Stdout.WriteString(strc)
}
// BuildStructFromFields builds a go struct from a slice of fields
func BuildStructFromFields(fields []string) string {
var buf bytes.Buffer
buf.WriteString("type ")
buf.WriteString("AutoGenerated")
buf.WriteString(" struct {\n")
for _, f := range fields {
f = strings.Trim(f, "\n")
buf.WriteString("\t" + ToPascal(f) + " ")
buf.WriteString("string")
// add struct tags
buf.WriteString(" `json:\"" + f + "\"`\n")
}
buf.WriteString("}\n")
return buf.String()
}
// ToPascal takes in a string in snake case and returns the PascalCase version
func ToPascal(s string) string {
// Split the string on underscores
parts := strings.Split(s, "_")
for i, p := range parts {
// Capitalize the string
parts[i] = strings.Title(p)
}
return strings.Join(parts, "")
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment