A tool to convert Go struct into a SQL table

Hey folks, I wrote a tool that converts Go structs into SQL query that’ll create a table with the struct’s fields. This is the first version, I do plan on improving it in the future. It is written in 100% Javascript as it is ideal for the task.

P.s : I wrote this after searching Google for a tool like this and it works best with postgresql

You can find it here : https://cheikhshift.github.io/struct-to-sql/

Source code here : https://github.com/cheikhshift/struct-to-sql

1 Like

Considering that we are on the “Golang Bridge” forum site, I may be biased, but I would argue that Javascript is hardly ideal for the task :laughing:

Anyway, this is a nice proof-of-concept. I would recommend:

  1. Use an actual Go syntax parser:

    Your code assumes that the Go struct name is on one line and each field is on each subsequent line until you get to the final closing }. If your input Go code has a syntax error, or is not formatted with the current gofmt implementation, it will not produce the correct output. For example:

    type Struct1 struct {
    type Struct2 struct {
        S string
        I int
    }
    
  2. The code does not generate the most optimal types for PostgreSQL. For example, a single byte in the struct should not become a VARCHAR in PostgreSQL. It should be char(1) or bytea.

  3. Add support for databases other than PostgreSQL, such as MySQL, SQLite3, Microsoft SQL Server, etc.

  4. Add support for different naming conventions. Not everyone uses “snake-case” and some people might be interested in using this code to generate SQL queries against pre-existing 3rd-party databases.


Disclaimer

I happen to be working on my own SQL-generator from Go struct definitions, so I am, perhaps, a bit “picky” about this!

3 Likes

If you wanted to use a Go syntax parser, you could possibly use WASM:

I like the idea of never sending any data back to the server. Matt Holt’s excellent curl to go and json to go don’t send anything back to the server and thus I can use them without privacy fears. So, keeping this running 100% in the browser is, in my opinion, ideal.

Anyway, great start. This is how many successful open source projects have started: by somebody creating a solution to a problem they have. Keep up the good work!

1 Like

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.