Baike.dev
All toolsOnline toolsAI codingTrendingOpen sourceNewsSubmit
Log in
< Back to tools
G

gen

> 数据库
Open source

Converts a database into gorm structs and RESTful api

1.4K stars0 likes3 views
WebsiteGitHub

About

Converts a database into gorm structs and RESTful api

gen

The gen tool produces a CRUD (Create, read, update and delete) REST api project template from a given database. The gen tool will connect to the db connection string analyze the database and generate the code based on the flags provided.

By reading details from the database about the column structure, gen generates a go compatible struct type with the required column names, data types, and annotations.

It supports gorm tags and implements some usable methods. Generated data types include support for nullable columns sql.NullX types or guregu null.X types and the expected basic built in go types.

gen is based / inspired by the work of Seth Shelnutt's db2struct, and Db2Struct is based/inspired by the work of ChimeraCoder's gojson package gojson.

CRUD Generation

This is a sample table contained within the ./example/sample.db Sqlite3 database. Using gen will generate the following struct.

sql
CREATE TABLE "albums"
(
    [AlbumId]  INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,
    [Title]    NVARCHAR(160) NOT NULL,
    [ArtistId] INTEGER NOT NULL,
    FOREIGN KEY ([ArtistId]) REFERENCES "artists" ([ArtistId])
		ON DELETE NO ACTION ON UPDATE NO ACTION
)

Transforms into

…

Code generation for a complete CRUD rest project is possible with DAO crud functions, http handlers, makefile, sample server are available. Check out some of the code generated samples.

Binary Installation

…

Usage

…

Building

The project contains a makefile for easy building and common tasks.

  • go get - get the relevant dependencies as a "go" software
  • make help - list available targets
  • make build - generate the binary ./gen
  • make example - run the gen process on the example SqlLite db located in ./examples place the sources in ./example Other targets exist for dev tasks.

Example

The project provides a sample SQLite database in the ./example directory. From the project Makefile can be used to generate the example code.

make example

The generated project will contain the following code under the ./example directory.

  • Makefile
    • useful Makefile for installing tools building project etc. Issue make to display help output.
  • .gitignore
    • git ignore for go project
  • go.mod
    • go module setup, pass --module flag for setting the project module default example.com/example
  • README.md
    • Project readme
  • app/server/main.go
    • Sample Gin Server, with swagger init and comments
  • api/.go
    • REST crud controllers
  • dao/.go
    • DAO functions providing CRUD access to database
  • model/.go
    • Structs representing a row for each database table

Generated Samples

  • GORM DAO CRUD Functions
  • SQLX DAO CRUD Functions
  • Http CRUD Handlers
  • Model
  • Protobuf Definition

The REST api server utilizes the Gin framework, GORM db api and Swag for providing swagger documentation

  • Gin
  • Swaggo
  • Gorm
  • packr2

Supported Databases

Currently Supported,

  • MariaDB
  • MySQL
  • PostgreSQL
  • Microsoft SQL Server
  • SQLite

Planned Support

  • Oracle

Supported Data Types

Most data types are supported, for Mysql, Postgres, SQLite and MS SQL. gen uses a mapping json file that can be used to add mapping types. By default, the internal mapping file is loaded and processed. If can be overwritten or additional types added by using the --mapping=extra.json command line option.

The default mapping.json file is located within the ./templates dir. Use gen --save=./templates to save the contents of the templates to ./templates. Below is a portion of the mapping file, showing the mapping for varchar.

json
    {
      "sql_type": "varchar",
      "go_type": "string",
      "protobuf_type": "bytes",
      "guregu_type": "null.String",
      "go_nullable_type": "sql.NullString"
    }

Advanced

The gen tool provides functionality to layout your own project format. Users have 2 options.

  • Provide local templates with the --templateDir= option - this will generate code using the local templates. Templates can either be exported from gen via the command gen --save ./mytemplates. This will save the embedded templates for local editing. Then you would specify the --templateDir= option when generating a project.

  • Passing --exec=../sample.gen on the command line will load the sample.gen script and execute it. The script has access to the table information and other info passed to gen. This allows developers to customize the generation of code. You could loop through the list of tables and invoke GenerateTableFile or GenerateFile. You can also perform operations such as mkdir, copy, touch, pwd.

Example - generate files from a template looping thru a map of tables.

Loop thru map of tables, key is the table name and value is ModelInfo. Creating a file using the table ModelInfo.

tableInfos := map[string]*ModelInfo

GenerateTableFile(tableInfos map[string]*ModelInfo, tableName, templateFilename, outputDirectory, outputFileName string, formatOutput bool)


{{ range $tableName , $table := .tableInfos }}
   {{$i := inc }}
   {{$name := toUpper $table.TableName -}}
   {{$filename  := printf "My%s.go" $name -}}

   {{ GenerateTableFile $.tableInfos $table.TableName  "custom.go.tmpl" "test" $filename true}}{{- end }}

Example - generate file from a template.

GenerateFile(templateFilename, outputDirectory, outputFileName string, formatOutput bool, overwrite bool)


{{ GenerateFile "custom.md.tmpl" "test" "custom.md" false false }}

Example - make a directory.


{{ mkdir "test/alex/test/mkdir" }}

Example - touch a file.


{{ touch "test/alex/test/mkdir/alex.txt" }}

Example - display working directory.


{{ pwd }}

Example - copy a file or directory from source to a target directory.

copy function updated to provide --include and --exclude patterns. Patterns are processed in order, an include preceeding an exclude will take precedence. Multiple include and excludes can be specified. Files ending with .table.tmpl will be processed for each table. Output filenames will be stored in the proper directory, with a name of the table with the suffix of the template extension. Files ending with .tmpl will be processed as a template and the filename will be the name of the template stripped with the .tmpl suffix.


{{ copy "../_test" "test" }}

{{ copy "./backend" "test/backend" "--exclude .idea|commands" "--exclude go.sum"  "--include .*" }}

{{ copy "./backend" "test/backend" "--include backend" "--include go.mod" "--exclude .*"  }}

You can also populate the context used by templates with extra data by passing the --context=<json file> option. The json file will be used to populate the context used when parsing templates.

File Generation

…

Struct naming

The ability exists to set a template that will be used for generating a struct name. By passing the flag --model_naming={{.}} The struct will be named the table name. Various functions can be used in the template to modify the name such as

You can use the argument --name_test=user in conjunction with the --model_naming or --file_name, to view what the naming would be.

Function Table Name Output
singular Users User
pluralize Users Users
title Users Users
toLower Users users
toUpper Users USERS
toLowerCamelCase Users users
toUpperCamelCase Users Users
toSnakeCase Users users

Struct naming Examples

Table Name: registration_source

Model Naming Format Generated Struct Name
{{.}} registration_source
Struct{{.}} Structregistration_source
Struct{{ singular .}} Structregistration_source
Struct{{ toLowerCamelCase .}} Structregistration_source
Struct{{ toUpperCamelCase .}} StructRegistration_source
Struct{{ toSnakeCase .}} Structregistration_source
Struct{{ toLowerCamelCase .}} Structtable_registration_source
Struct{{ toUpperCamelCase .}} StructTable_registration_source
Struct{{ toSnakeCase .}} Structtable_registration_source
Struct{{ toSnakeCase ( replace . "table_" "") }} Structregistration_source

Notes

  • MySql, Mssql, Postgres and Sqlite have a database metadata fetcher that will query the db, and update the auto increment, primary key and nullable info for the gorm annotation.
  • Tables that have a non-standard primary key (NON integer based or String) the table will be ignored.

DB Meta Data Loading

DB Type Nullable Primary Key Auto Increment Column Len default Value create ddl
sqlite y y y y y y y
postgres y y y y y y n
mysql y y y y y y y
ms sql y y y y y y n

Version History

  • v0.9.27 (08/04/2020)
    • Updated '--exec' mode to provide various functions for processing
    • copy function updated to provide --include and --exclude patterns. Patterns are processed in order, an include preceeding an exclude will take precedence. Multiple include and excludes can be specified. Files ending with .table.tmpl will be processed for each table. Output filenames will be stored in the proper directory, with a name of the table with the suffix of the template extension. Files ending with .tmpl will be processed as a template and the filename will be the name of the template stripped with the .tmpl suffix.
    • When processing templates, files generated with a .go extension will be formatted with the go fmt.
  • v0.9.26 (07/31/2020)
    • Release scripting
    • Added custom script functions to copy, mkdir, touch, pwd
    • Fixed custom script exec example
  • v0.9.25 (07/26/2020)
    • Adhere json-fmt flag for all JSON response so when camel or lower_camel is specified, fields name in GetAll variant and DDL info will also have the same name format
    • Fix: Build information embedded through linker in Makefile is not consistent with the variable defined in main file.
    • Added --scheme and --listen options. This allows compiled binary to be used behind reverse proxy.
    • In addition, template for generating URL was fixed, i.e. when PORT is 80, then PORT is omitted from URL segment.
  • v0.9.24 (07/13/2020)
    • Fixed array bounds issue parsing mysql db meta
  • v0.9.23 (07/10/2020)
    • Added postgres types: bigserial, serial, smallserial, bigserial, float4 to mapping.json
  • v0.9.22 (07/08/2020)
    • Modified gogo.proto check to use GOPATH not hardcoded.
    • Updated gen to error exit on first error encountered
    • Added color output for error
    • Added --no-color option for non colorized output
  • v0.9.21 (07/07/2020)
    • Repacking templates, update version number in info.
  • v0.9.20 (07/07/2020)
    • Fixed render error in router.go.tmpl
    • upgraded project to use go.mod 1.14
  • v0.9.19 (07/07/2020)
    • Added --windows flag to write files with CRLF windows line endings, otherwise they are all unix based LF line endings
  • v0.9.18 (06/30/2020)
    • Fixed naming in te

Issues· 29 open

View all issuesOpen on GitHub

No open issues yet, or sync has not completed.

> Tags

Godatabasedatabasesgeneratorgorm

No comments yet. Be the first to share.

> Details

PublishedAug 1, 2026
UpdatedSep 17, 2026
Category数据库
PricingOpen source

> Related tools

P
PostgreSQL
功能强大的开源关系型数据库
R
Redis
内存数据结构存储,常用作缓存与队列
M
MySQL
广泛使用的开源关系型数据库