项目作者: fraenky8

项目描述 :
convert your database tables to structs easily
高级语言: Go
项目地址: git://github.com/fraenky8/tables-to-go.git
创建时间: 2016-08-04T18:06:22Z
项目社区:https://github.com/fraenky8/tables-to-go

开源协议:MIT License

下载


Tables-to-Go

convert your database tables to structs easily

A small and convenient tool supporting development against a changing
database schema.

Tables change, run the tool, get your structs!

Go Report Card
GoDoc
Build & Test
Code Coverage

Requirements

  • Go 1.23+

Install

This project provides a make file but can also simply be installed with the
go-install command.

Get the latest stable release version:

  1. go install github.com/fraenky8/tables-to-go/v2@latest

Get the latest changes from master:

  1. go install github.com/fraenky8/tables-to-go/v2@master

To enable SQLite3 support, clone the repo manually and run the make file:

  1. make sqlite3

See this PR why it’s
disabled by default.

Getting Started

  1. tables-to-go -v -of ../path/to/my/models

This gets all tables of a local running PostgreSQL database. Therefore, it uses
the database postgres, schema public and user postgres with no password.
Flag -v is verbose mode, -of is the output file path where the go files
containing the structs will get created (default: current working directory).

Features

  • convert your tables to structs
  • table with name a_foo_bar will become file AFooBar.go with struct AFooBar
  • properly formatted files with imports
  • automatically typed struct fields, either with sql.Null* or primitive pointer types
  • struct fields with db-tags for ready to use in database code
  • partial support for Masterminds/structable
    • only primary key & auto increment columns supported
    • struct fields with stbl tags
    • ability to generate structs only for Masterminds/structable:
      • without db-tags
      • with or without structable.Recorder
  • currently supported:
    • PostgreSQL (9.5 tested)
    • MySQL (5.5+, 8 tested)
    • SQLite (3 tested)
  • currently, the following basic data types are supported:
    • numeric: integer, serial, double, real, float
    • character: varying, text, char, varchar, binary, varbinary, blob
    • date/time: timestamp, date, datetime, year, time with time zone, timestamp
      with time zone, time without time zone, timestamp without time zone
    • others: boolean

Examples

Assuming you have the following table definition (PostgreSQL):

  1. CREATE TABLE some_user_info (
  2. id SERIAL NOT NULL PRIMARY KEY,
  3. first_name VARCHAR(20),
  4. last_name VARCHAR(20) NOT NULL,
  5. height DECIMAL
  6. );

Run the following command (default local PostgreSQL instance):

  1. tables-to-go

The following file SomeUserInfo.go with default package dto (data transfer
object) will be created:

  1. package dto
  2. import (
  3. "database/sql"
  4. )
  5. type SomeUserInfo struct {
  6. ID int `db:"id"`
  7. FirstName sql.NullString `db:"first_name"`
  8. LastName string `db:"last_name"`
  9. Height sql.NullFloat64 `db:"height"`
  10. }

The column id got automatically converted to upper-case to follow the idiomatic
go guidelines.
See here
for more details.
Words which gets converted can be found
here.


This behaviour can be disabled by providing the command-line flag -no-initialism.

Running on remote database server (eg. Mysql@Docker)

  1. tables-to-go -v -t mysql -h 192.168.99.100 -d testdb -u root -p mysecretpassword

PostgreSQL example with different default schema but default database postgres:

  1. tables-to-go -v -t pg -h 192.168.99.100 -s test -u postgres -p mysecretpassword

Note: since database type pg is default, following command will be equivalent:

  1. tables-to-go -v -h 192.168.99.100 -s test -u postgres -p mysecretpassword

You can also specify the package or prefix and suffix.

  1. tables-to-go -v -t mysql -h 192.168.99.100 -d testdb -u root -p mysecretpassword -pn models -pre model_ -suf _model

With same table given above, following file with Name ModelSomeUserInfoModel.go
will be created:

  1. package models
  2. import (
  3. "database/sql"
  4. )
  5. type ModelSomeUserInfoModel struct {
  6. ID int `db:"id"`
  7. FirstName sql.NullString `db:"first_name"`
  8. LastName string `db:"last_name"`
  9. Height sql.NullFloat64 `db:"height"`
  10. }

Filter for specific tables via (multiple) -table flags:

  1. tables-to-go -v -of ../path/to/my/models -table foobar -table foo,bar,baz

Where Are The JSON-Tags?

This is a common question asked by contributors and bug reporters.

Fetching data from a database and representation of this data in the end
(JSON, HTML template, cli, …) are two different concerns and should be
decoupled. Therefore, this tool will not generate json tags for the structs.

There are tools like gomodifytags which
enables you to generate json tags for existing structs.
The call for this tool applied to the example above looks like the following:

  1. gomodifytags -file SomeUserInfo.go -w -all -add-tags json

This adds the json tags directly to the file:

  1. type SomeUserInfo struct {
  2. ID int `db:"id" json:"id"`
  3. FirstName sql.NullString `db:"first_name" json:"first_name"`
  4. LastName string `db:"last_name" json:"last_name"`
  5. Height sql.NullFloat64 `db:"height" json:"height"`
  6. }

Command-line Flags

Print usage with -? or -help

  1. Usage of tables-to-go:
  2. -? shows help and usage
  3. -d string
  4. database name (default "postgres")
  5. -f force; skip tables that encounter errors
  6. -fn-format value
  7. format of the filename: camelCase (c, default) or snake_case (s) (default c)
  8. -format value
  9. format of struct fields (columns): camelCase (c) or original (o) (default c)
  10. -h string
  11. host of database (default "127.0.0.1")
  12. -help
  13. shows help and usage
  14. -no-initialism
  15. disable the conversion to upper-case words in column names
  16. -null value
  17. representation of NULL columns: sql.Null* (sql) or primitive pointers (native|primitive) (default sql)
  18. -of string
  19. output file path, default is current working directory (default "/Users/zalora_user/Coding/Go/src/github.com/fraenky8/tables-to-go")
  20. -p string
  21. password of user
  22. -pn string
  23. package name (default "dto")
  24. -port string
  25. port of database host, if not specified, it will be the default ports for the supported databases
  26. -pre string
  27. prefix for file- and struct names
  28. -s string
  29. schema name (default "public")
  30. -socket string
  31. The socket file to use for connection. If specified, takes precedence over host:port.
  32. -sslmode string
  33. Connect to database using secure connection. (default "disable")
  34. The value will be passed as is to the underlying driver.
  35. Refer to this site for supported values: https://www.postgresql.org/docs/current/libpq-ssl.html
  36. -structable-recorder
  37. generate a structable.Recorder field
  38. -suf string
  39. suffix for file- and struct names
  40. -t value
  41. type of database to use, currently supported: [pg mysql sqlite3] (default pg)
  42. -table value
  43. Filter for the specified table(s). Can be used multiple times or with comma separated values without spaces. Example: -table foobar -table foo,bar,baz
  44. -tags-no-db
  45. do not create db-tags
  46. -tags-structable
  47. generate struct with tags for use in Masterminds/structable (https://github.com/Masterminds/structable)
  48. -tags-structable-only
  49. generate struct with tags ONLY for use in Masterminds/structable (https://github.com/Masterminds/structable)
  50. -u string
  51. user to connect to the database
  52. -v verbose output
  53. -version
  54. show version and build information
  55. -vv
  56. more verbose output

Contributing

If you find any issues or missing a feature, feel free to contribute or make
suggestions! You can fork the repository and use a feature branch too. Feel free
to send me a pull request. The PRs have to come with appropriate unit tests,
documentation of the added functionality and updated README with optional
examples.

To start developing clone via git or use go’s get command to fetch this
project.

This project uses go modules so
make sure when adding new dependencies to update the go.mod file and the
vendor directory:

  1. go mod tidy
  2. go mod vendor

Licensing

The code in this project is licensed under MIT license.