Converts a database into gorm structs and RESTful api
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.
This is a sample table contained within the ./example/sample.db Sqlite3 database. Using gen will generate the following struct.
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
)…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.
……The project contains a makefile for easy building and common tasks.
go get - get the relevant dependencies as a "go" softwaremake help - list available targetsmake build - generate the binary ./genmake example - run the gen process on the example SqlLite db located in ./examples place the sources in ./example
Other targets exist for dev tasks.The project provides a sample SQLite database in the ./example directory. From the project Makefile can be used to generate the example code.
make exampleThe generated project will contain the following code under the ./example directory.
make to display help output.--module flag for setting the project module default example.com/exampleThe REST api server utilizes the Gin framework, GORM db api and Swag for providing swagger documentation
Currently Supported,
Planned Support
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.
{
"sql_type": "varchar",
"go_type": "string",
"protobuf_type": "bytes",
"guregu_type": "null.String",
"go_nullable_type": "sql.NullString"
}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.
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 }}
GenerateFile(templateFilename, outputDirectory, outputFileName string, formatOutput bool, overwrite bool)
{{ GenerateFile "custom.md.tmpl" "test" "custom.md" false false }}
{{ mkdir "test/alex/test/mkdir" }}
{{ touch "test/alex/test/mkdir/alex.txt" }}
{{ pwd }}
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.
…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 |
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 |
| 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 |
No open issues yet, or sync has not completed.