SkillAgentSearch skills...

Gen

Converts a database into gorm structs and RESTful api

Install / Use

/learn @smallnest/Gen
About this skill

Quality Score

0/100

Supported Platforms

Universal

README

gen

License GoDoc travis Go Report Card

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.

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

type Album struct {
	//[ 0] AlbumId                                        integer              null: false  primary: true   auto: true   col: integer         len: -1      default: []
	AlbumID int `gorm:"primary_key;AUTO_INCREMENT;column:AlbumId;type:INTEGER;" json:"album_id" db:"AlbumId" protobuf:"int32,0,opt,name=album_id"`
	//[ 1] Title                                          nvarchar(160)        null: false  primary: false  auto: false  col: nvarchar        len: 160     default: []
	Title string `gorm:"column:Title;type:NVARCHAR(160);size:160;" json:"title" db:"Title" protobuf:"string,1,opt,name=title"`
	//[ 2] ArtistId                                       integer              null: false  primary: false  auto: false  col: integer         len: -1      default: []
	ArtistID int `gorm:"column:ArtistId;type:INTEGER;" json:"artist_id" db:"ArtistId" protobuf:"int32,2,opt,name=artist_id"`
}

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

## install gen tool (should be installed to ~/go/bin, make sure ~/go/bin is in your path.

## go version < 1.17
$ go get -u github.com/smallnest/gen

## go version == 1.17
$ go install github.com/smallnest/gen@latest

## download sample sqlite database
$ wget https://github.com/smallnest/gen/raw/master/example/sample.db

## generate code based on the sqlite database (project will be contained within the ./example dir)
$ gen --sqltype=sqlite3 \
   	--connstr "./sample.db" \
   	--database main  \
   	--json \
   	--gorm \
   	--guregu \
   	--rest \
   	--out ./example \
   	--module example.com/rest/example \
   	--mod \
   	--server \
   	--makefile \
   	--json-fmt=snake \
   	--generate-dao \
   	--generate-proj \
   	--overwrite

## build example code (build process will install packr2 if not installed)
$ cd ./example
$ make example

## binary will be located at ./bin/example
## when launching make sure that the SQLite file sample.db is located in the same dir as the binary
$ cp ../../sample.db  .
$ ./example


## Open a browser to http://127.0.0.1:8080/swagger/index.html

## Use wget/curl/httpie to fetch via command line
http http://localhost:8080/albums
curl http://localhost:8080/artists

Usage

Usage of gen:
	gen [-v] --sqltype=mysql --connstr "user:password@/dbname" --database <databaseName> --module=example.com/example [--json] [--gorm] [--guregu] [--generate-dao] [--generate-proj]
git fetch up
           sqltype - sql database type such as [ mysql, mssql, postgres, sqlite, etc. ]


Options:
  --sqltype=mysql                                          sql database type such as [ mysql, mssql, postgres, sqlite, etc. ]
  -c, --connstr=nil                                        database connection string
  -d, --database=nil                                       Database to for connection
  -t, --table=                                             Table to build struct from
  -x, --exclude=                                           Table(s) to exclude
  --templateDir=                                           Template Dir
  --fragmentsDir=                                          Code fragments Dir
  --save=                                                  Save templates to dir
  --model=model                                            name to set for model package
  --model_naming={{FmtFieldName .}}                        model naming template to name structs
  --field_naming={{FmtFieldName (stringifyFirstChar .) }}  field naming template to name structs
  --file_naming={{.}}                                      file_naming template to name files
  --dao=dao                                                name to set for dao package
  --api=api                                                name to set for api package
  --grpc=grpc                                              name to set for grpc package
  --out=.                                                  output dir
  --module=example.com/example                             module path
  --overwrite                                              Overwrite existing files (default)
  --no-overwrite                                           disable overwriting files
  --windows                                                use windows line endings in generated files
  --no-color                                               disable color output
  --context=                                               context file (json) to populate context with
  --mapping=                                               mapping file (json) to map sql types to golang/protobuf etc
  --exec=                                                  execute script for custom code generation
  --json                                                   Add json annotations (default)
  --no-json                                                Disable json annotations
  --json-fmt=snake                                         json name format [snake | camel | lower_camel | none]
  --xml                                                    Add xml annotations (default)
  --no-xml                                                 Disable xml annotations
  --xml-fmt=snake                                          xml name format [snake | camel | lower_camel | none]
  --gorm                                                   Add gorm annotations (tags)
  --protobuf                                               Add protobuf annotations (tags)
  --proto-fmt=snake                                        proto name format [snake | camel | lower_camel | none]
  --gogo-proto=                                            location of gogo import 
  --db                                                     Add db annotations (tags)
  --guregu                                                 Add guregu null types
  --copy-templates                                         Copy regeneration templates to project directory
  --mod                                                    Generate go.mod in output dir
  --makefile                                               Generate Makefile in output dir
  --server                                                 Generate server app output dir
  --generate-dao                                           Generate dao functions
  --generate-proj                                          Generate project readme and gitignore
  --rest                                                   Enable generating RESTful api
  --run-gofmt                                              run gofmt on output dir
  --listen=                                                listen address e.g. :8080
  --scheme=http                                            scheme for server url
  --host=localhost                                         host for server
  --port=8080                                              port for server
  --swagger_version=1.0                                    swagger version
  --swagger_path=/                                         swagger base path
  --swagger_tos=                                           swagger tos url
  --swagger_contact_name=Me                                swagger contact name
  --swagger_contact_url=http://me.com/terms.html           swagger contact url
  --swagger_contact_email=me@me.com                        swagger contact email
  -v, --verbose                                            Enable verbose output
  --name_test=                                             perform name test using the --model_naming or --file_naming options
  -h, --help                                               Show usage message
  --version                                                Show version


Building

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

  • go get - get the relevan
View on GitHub
GitHub Stars1.4k
CategoryData
Updated1mo ago
Forks227

Languages

Go

Security Score

100/100

Audited on Feb 28, 2026

No findings